Search code examples
pythonclass-variables

Python: self vs type(self) and the proper use of class variables


When using a class variable in Python, one can access and (if it's mutable) directly manipulate it via "self" (thanks to references) or "type(self)" (directly), while immutable variables (e.g., integers) apparently get shadowed by new instance objects when you just use "self".

So, when dealing with Python class variables, is it preferable/Pythonic to simply always use "type(self)" for working with class variables referred to from within class methods?

(I know class variables are sometimes frowned upon but when I work with them I want to access them in a consistent way (versus one way if they are immutable types and another way if they are mutable.)

Edit: Yes, if you modify the value an immutable you get a new object as a result. The side effect of modifying the value of a mutable object is what led to this question - "self" will give you a reference you can use to change the class variable without shadowing it, but if you assign a new object to it it will shadow it. Using classname.classvar or type(self).classvar or self.__class__ ensures you are always working with the class variable, not just shadowing it (though child classes complicate this as has been noted below).


Solution

  • After speaking with others offline (and per @wwii's comment on one of the answers here), it turns out the best way to do this without embedding the class name explicitly is to use self.__class__.attribute.

    (While some people out there use type(self).attribute it causes other problems.)