Whenever I'm defining a class which has a number of parameters I often find myself doing something like this
class myClass(object):
def __init__(self,param1,param2,param3, ...):
self.param1 = param1
self.param2 = param2
self.param3 = param3
...
My question is: is there a smarter, Pythonier way of doing this?
Thanks, Alex.
You could accept a variable number of named arguments and automatically set them, like this:
class MyClass(object):
def __init__(self, **kwargs): # variable named arguments
for k, v in kwargs.items():
setattr(self, k, v) # set the value of self.k to v, same as self.k = v
test = MyClass(param1="param1", param2="param2")
print test.param1 # "param1"
setattr documentation
You can pass your parameters as a keyword arguments
: -
def __init__(self, **kwargs):
self.args = kwargs
Then you will instantiate your class like this: -
myClassObj = MyClass(a=12, b="abc")
Then your args
dict will contain those arguments as key-value pair: -
{'a':12, 'b':'abc'}
to access the attributes: -
myClassObj.args['a']
myClassObj.args['b']
You can also pass a combination of various arguments. There are 4 kinds of arguments you can have in any function: -
In that order only. So the typical syntax of a function declaration is: -
def func(positional_arg, default_arg, *nkwargs, **kwargs)
See documentation for more on defining functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With