I have a python class I want to instantiate and the __init__ definition has a lot of parameters (10+). Is there a clean way to instantiate a class who's __init__ takes a lot of params?
For example:
class A(object):
def __init__(self, param1, param2, param3,...param13):
// create an instance of A
my_a = new A(param1="foo", param2="bar", param3="hello"....)
Is there a cleaner way to do this? like passing in a dictionary or something? Or better, is there an expected convention?
-
3WHY does the init have so many parameters?Tyler Eaves– Tyler Eaves2012年03月27日 19:38:23 +00:00Commented Mar 27, 2012 at 19:38
-
1I REALLY Hope your params are not really named like this!ThiefMaster– ThiefMaster2012年03月27日 19:45:21 +00:00Commented Mar 27, 2012 at 19:45
4 Answers 4
Yes, you can use a dict to collect the parameters:
class A(object):
def __init__(self, param1, param2, param3):
print param1, param2, param3
params = {'param1': "foo", 'param2': "bar", 'param3': "hello"}
# no 'new' here, just call the class
my_a = A(**params)
See the unpacking argument lists section of the Python tutorial.
Also, // isn't a comment in Python, it's floor division. # is a comment. For multi-line comments, '''You can use triple single quotes''' or """triple double quotes""".
Comments
There is no new keyword in Python. You just invoke the class name as you would a function.
You may specify keyword arguments using a dictionary by prefixing the dictionary with **, for example:
options = {
"param1": "foo",
"param2": "bar",
"param3": "baz"
}
my_a = A(**options)
If you're going to be defining all of the values at once, using a dictionary doesn't really give you any advantage over just specifying them directly while using extra whitespace for clairity:
my_a = A(
param1 = "foo",
param2 = "bar",
param3 = "baz"
)
2 Comments
args, the convention in Python is for args to be a list of positional parameters, not a dict.dict.its not good passing too many arguments to a constructor. but if you want to do this,try:
class A(object):
def __init__(self, *args,**kwargs):
"""
provide list of parameters and documentation
"""
print *args, **kwargs
params = {'param1': "foo", 'param2': "bar", 'param3': "hello"}
a = A(**params)
Comments
Generally, having that many parameters is often a sign that a class is too complicated and should be split up.
If that doesn't apply, pass up a dictionary, or a special parameter object.