Isn't there a better way?
Peter Otten
__peter__ at web.de
Fri Jul 21 12:04:00 EDT 2006
T wrote:
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
>
> # Class that does the real work
> bar = Processor()
> bar.index = foo.options.index
> bar.output = foo.options.output
> bar.run()
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another. Isn't there a better way???
Not sure if this is better, but you can use OptionParser to set attributes
on arbitrary objects, including your Processor instance:
>>> class Processor(object):
... def __init__(self):
... self.verbose = False
... self.index = 42
...
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-v", "--verbose", action="store_true")
<Option at 0x40294aac: -v/--verbose>
>>> parser.add_option("-i", "--index", type="int")
<Option at 0x40294a6c: -i/--index>
>>> p = Processor()
>>> parser.parse_args(args=["-i75", "-v"], values=p)
(<__main__.Processor object at 0x40298e0c>, [])
>>> p.verbose, p.index
(True, 75)
Peter
More information about the Python-list
mailing list