Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 775
MartyMacGyver Avatar asked Oct 16 '25 03:10

MartyMacGyver


2 Answers

You'll probably want to access them with the actual type name, rather than either self or type(self).

The effect you're seeing has nothing to do with mutability. If you were to do

class Foo(object):
    x = []
    def __init__(self):
        self.x = [1]

the assignment in __init__ would create a new list and assign it to the instance attribute x, ignoring the class attribute, even though Foo.x is a mutable object. Whenever you want to assign to an attribute, you need to use the object it was actually defined on.

Note that modifying the attribute through type(self) fails in the case of inheritance:

class Foo(object):
    x = 1
    def modify_x(self, x):
        type(self).x = x

class Bar(Foo): pass

Foo().modify_x(2) # modifies Foo.x
Bar().modify_x(3) # modifies Bar.x, the wrong attribute
like image 81
user2357112 supports Monica Avatar answered Oct 18 '25 20:10

user2357112 supports Monica


python -c 'import this'
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

I will suggest these for reference

Beautiful is better than ugly.
Simple is better than complex.
Readability counts.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
If the implementation is hard to explain, it's a bad idea.

and my suggestion is to use direct attribute reference because it is probably what the language designers intended.

like image 43
Andrew Johnson Avatar answered Oct 18 '25 19:10

Andrew Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!