Information Technology Reference
In-Depth Information
in the Integration hierarchy.
"""
def __init__(self):
self.default()
return
def default(self):
"""Assign appropriate default values to all parameters."""
self.a = 0
self.b = 1
self.npoints = 10
# default f(x)=1+x:
self.f = Function('1+x', independent_variable='x')
self.method = "Trapezoidal"
# alternative: could use a dictionary and __getitem__
def read(self, argv=sys.argv[1:], short_opt="", long_opt=""):
"""Read from the command line."""
from cmldict import cmldict
defaults = { 'a' : 0, 'b' : 1, 'n' : 10,
'f' : Function("1+x"), 'm' : "Trapezoidal" }
p = cmldict(argv, cmlargs=defaults, validity=0)
self.a = p['a']
self.b = p['b']
self.f = Function(p['f'])
self.npoints = p['n']
self.method = p['m']
# alternative manual parsing by traversing argv:
for i in range(0,len(argv),2):
if argv[i] == "-a": self.a = float(argv[i+1])
if argv[i] == "-b": self.b = float(argv[i+1])
if argv[i] == "-n": self.n = int(argv[i+1])
if argv[i] == "-f": self.n = Function(argv[i+1])
if argv[i] == "-m": self.method = argv[i+1]
def write(self):
print "a=%g b=%g f='%s' n=%d method=%s" % \
(self.a, self.b, self.f.__name__, \
self.npoints, self.method)
def create(self):
"""Create subclass of Integration"""
code = "i = %s(self)" % self.method
exec(code) # turn string into Python code
return i
Note that the create function is very simple, because the string in self.method
is supposed to coincide with a subclass name in the Integration hierarchy. We can
therefore construct a string code containing the construction of the proper subclass
instance and use exec to execute this code segment. Alternatively, we could have
used an if-else test, as we did in the corresponding create method in the Java code.
Here is an example on a typical main program using an Integration prm
instance and an Integration subclass instance to evaluate an integral:
p = Integration_prm()
p.read(sys.argv[1:])
p.write()
i = p.create()
Search WWH ::




Custom Search