Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self syntax in python

Tags:

python

oop

class

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.

like image 448
Alex S Avatar asked Dec 15 '22 17:12

Alex S


2 Answers

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

like image 180
scripts Avatar answered Jan 06 '23 22:01

scripts


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: -

  • Positional Argument
  • Default Argument
  • Non-Keyword Argument
  • Keyword argument.

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.

like image 26
Rohit Jain Avatar answered Jan 06 '23 23:01

Rohit Jain