8

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?

2
  • 3
    WHY does the init have so many parameters? Commented Mar 27, 2012 at 19:38
  • 1
    I REALLY Hope your params are not really named like this! Commented Mar 27, 2012 at 19:45

4 Answers 4

10

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""".

Sign up to request clarification or add additional context in comments.

Comments

6

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

You shouldn't call it args, the convention in Python is for args to be a list of positional parameters, not a dict.
In regards to defining them all at once -- if you're going to use the same parameters in multiple places, you only have to have them in your code once if you use a dict.
4

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

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.