Python stand alone syntax

Whenever I define a class that has a number of parameters, I often find that I am 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 to do this?

Thanks, Alex.

+4
source share
3 answers

You can take a variable number of named arguments and set them automatically, for example:

 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

+9
source

You can pass your parameters as keyword arguments : -

 def __init__(self, **kwargs): self.args = kwargs 

Then you will create an instance of your class as follows: -

 myClassObj = MyClass(a=12, b="abc") 

Then your args dict will contain these arguments as a key-value pair: -

 {'a':12, 'b':'abc'} 

to access attributes: -

 myClassObj.args['a'] myClassObj.args['b'] 

You can also pass a combination of different arguments. There are four types of arguments that you can have in any function: -

  • Positional argument
  • Default argument
  • Keyless argument.
  • Keyword Argument.

Only in that order. Thus, the typical syntax for declaring a function is: -

 def func(positional_arg, default_arg, *nkwargs, **kwargs) 

For more information on defining functions, see.

+3
source

You can do something like:

 def __init__(self,*args): _init_args = ('param1','param2','param3') if len(_init_args) != len(args): raise TypeError('__init__ takes {nargs} args'.format(nargs=len(_init_args))) for k,v in zip(_init_args,*args): setattr(self,k,v) 

But I really don't think this is much better than your original solution or the solution sent by sean . The advantage of this sean answer is that the user does not need to know what the attribute names in your class are. It behaves a bit more like a declared function:

 def __init__(self,arg1,arg2,arg3): ... 

Although there are still differences.

0
source

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


All Articles