lots of similar classes?
boncelet
boncelet at udel.edu
Tue Jan 21 11:08:32 EST 2003
Thanks to all who responded. I suspected there were better ways and
now I have several to try out.
Let me summarize the ideas:
1. from Duncan Booth:
>class A(Super):
> def __init__(self, name='a', **args):
> Super.__init__(self, name, **args)
I thought of this one shortly after I sent me inital message. This is
part of what I'm currently using. I originally wanted the user to be
able to specify the most common args by position, but realized that is
error-prone as well.
2. from Beni Cherniavsky:
> Besides using ``**kwargs``, if the only difference is the default value of
> `name`, consider getting it from a class attribute (set in each subclass)
> and not overriding __init__ at all.
The class attribute idea is very helpful for me. This seems to be
best for all my subclasses (maybe 30-50 of them). I can write a
generic super class and use class attributes to differentiate between
the subclasses.
3. from Mike Fletcher:
> With Python 2.2.x, this will work:
> class X(object):
> def __init__( self, name='blah', y=2,z=3,m=4):
...
> class Y( X ):
> def __init__( self, name='haha', *args, **named ):
> super( Y, self).__init__( name, *args, **named )
I didn't know this worked. Will have to try it out. This is cool.
4. Roberto Cavada gave a suggestion that is above me. Sorry.
5. Hans Nowak suggests using an "options class". Very neat idea, also
one I have to test.
Thanks to all,
Charlie Boncelet
Hans Nowak <wurmy at earthlink.net> wrote in message news:<3E2C2F7B.8070606 at earthlink.net>...
> boncelet wrote:
>
> > 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)
> >
> > 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,
More information about the Python-list
mailing list