Alex S
Alex S

Reputation: 1065

Self syntax in python

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.

Upvotes: 4

Views: 543

Answers (3)

mgilson
mgilson

Reputation: 310167

You could 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 posted by sean. The advantage of this over sean's answer is that the user doesn't need to know what the names of the attributes in your class are. It behaves a little bit more like a function declared:

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

Although there are still differences.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213361

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.

Upvotes: 3

scripts
scripts

Reputation: 1470

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

Upvotes: 9

Related Questions