Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcut for `self.somevariable = somevariable` in a Python class constructor?

Constructors in Python often look like this:

class SomeClass:
    def __init__(self, a, b = None, c = defC):
        self.a = a
        self.b = b or []
        self.c = c

Is there a shortcut for this, e.g. to simply define __init__(self,**kwargs) and use the keys as properties of self?

like image 520
Tobias Kienzler Avatar asked Aug 30 '12 06:08

Tobias Kienzler


1 Answers

One idiom I've seen is self.__dict__.update(locals()). If you run it right at the beginning of the method, this will update the object's dictionary with the arguments (since those are the only locals at the beginning of the method). If you pass in **kwargs you can do self.__dict__.update(**kwargs).

Of course, this is a fragile approach. It can lead to puzzling bugs if you accidentally pass in an argument that masks an existing attribute. For instance, if your class has a .doSomething() method and you accidentally pass doSomething=1 to the constructor, it will override the method and cause an error later if you try to call that method. For this reason it's better not to do this except in certain trivial cases (e.g., some sort of proxy object whose only purpose is to serve as a "bag" holding a few attributes).

like image 69
BrenBarn Avatar answered Sep 22 '22 10:09

BrenBarn