lots of similar classes?
Hans Nowak
wurmy at earthlink.net
Mon Jan 20 12:14:41 EST 2003
boncelet wrote:
> I want to create lots of similar classes and wonder what's the
> best/most efficient way.
>
> Pseudo-code looks like this:
>
> class Super:
> def __init__(self,name,lots_of_other_arguments):
> self.name=name
> <<set rest of arguments, etc>>
>
> class A(Super):
> def __init__(self,name='a',lots_of_other_arguments):
> Super.__init__(self,name,lots_of_other_arguments)
>
> There will be lots of these, eg., A, B, C etc. Most of these will
> differ only in the name argument. In a few, I might want to use only
> a subset of the "other arguments".
>
> My problem is rewriting the "lot_of_other_arguments" over and over
> again seems wasteful, error-prone, and fragile. Is there a better
> way?
To take a page from Martin Fowler's book, lots of arguments for a method is a
"code smell". Consider writing a separate class for this. I regularly use a
variant of the following, especially when command line options translate to
options in a class:
class Options:
def __init__(self):
self.foo = ""
self.bar = None
# ...etc...
options = Options()
# set some options
options.baz = "bletch"
class MyClass:
def __init__(self, name, options):
self.options = options
myclass = MyClass("foo", options)
Now, your class uses an instance of Options to hold all these variables, rather
than having them in its own namespace. Much easier to pass around.
HTH,
--
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
Soon: http://zephyrfalcon.org/
More information about the Python-list
mailing list