Creating objects in python

I have a python class that I want to create, and the __init__ definition has many parameters (10+). Is there an easy way to create an instance of a class that __init__ takes up a lot of parameters?

For instance:

 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? for example, passing in a dictionary or something else? Or better, is there an expected convention?

+4
source share
4 answers

Yes, you can use dict to collect 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 section on unpacking arguments in a Python lesson.

Also, // not a comment in Python, it's a gender separation. # is a comment. For multi-line comments, '''You can use triple single quotes''' or """triple double quotes""" .

+6
source

Python does not have the new keyword. You simply call the class name as a function.

You can specify keyword arguments using a dictionary, the dictionary prefix with ** , for example:

 options = { "param1": "foo", "param2": "bar", "param3": "baz" } my_a = A(**options) 

If you intend to define all values ​​at once, using a dictionary does not give you any advantages over simply specifying them directly, using extra spaces for clairity:

 my_a = A( param1 = "foo", param2 = "bar", param3 = "baz" ) 
+3
source

it is not well passed too many arguments to the 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) 
+3
source

As a rule, the presence of many parameters is often a sign that the class is too complex and should be divided.

If this does not apply, skip the dictionary or special parameter object.

+1
source

Source: https://habr.com/ru/post/1403731/


All Articles