Reputation: 10765
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?
Upvotes: 8
Views: 13901
Reputation: 8055
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)
Upvotes: 4
Reputation: 176780
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"""
.
Upvotes: 10
Reputation: 45039
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.
Upvotes: 1
Reputation: 129775
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"
)
Upvotes: 6