[Tutor] class initialization with a lot of parameters
Lie Ryan
lie.1296 at gmail.com
Tue Nov 10 15:26:07 CET 2009
C.T. Matsumoto wrote:
> Hello All,
>
> I'm making a class and the parameters I'm feeding the class is getting
> quite large. I'm up
> to 8 now. Is there any rules of thumb for classes with a lot of
> parameters? I was thinking
> to put the parameters into a tuple and then in the __init__ of the
> class, iterate over the tuple
> and assign attributes.
>
> Right now my class basically looks like this:
>
> class Foo(object):
> def __init__(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8):
> ...
>
There are several "tricks":
1. pass a tuple
class Foo(object):
def __init__(self, args):
....
Foo(("blah", 1, 2, 3))
bad, just adds more parentheses and make argument unpacking more
complex, as Dave Angel said, an exception would be if the values are
related like coordinates
2. use default value and named argument
class Foo(object):
def __init__(self, arg0="", arg1=1, arg2=2, arg3=3):
....
Foo("blah")
simplifies the caller, but the function signature is a bit complex. You
might want to split the signature into lines:
def __init__(self,
arg0="",
arg1=1,
arg2=2,
arg3=3):
3. use *args and/or **kwargs
class Foo(object):
def __init__(self, *args):
....
unpacking argument becomes complex
4. your class might be doing too much! Look for ways to split it into
several smaller classes
More information about the Tutor
mailing list