问题
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).
回答1:
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
回答2:
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.
回答3:
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.)
回答4:
https://bitbucket.org/larry/cpython350/pull-requests/15/issue-24912-prevent-class-assignment/diff
In common cases they work the same (probably you should use YouClass.NameAttribute to avoid problems with later inheritance). In short the difference was till Python 3.5. The problem was issue #24912 (not allowing assingment in all cases). Example: an immutable type like int was alocated staticalli, and HEAPTYPE rules accidentally where stoping from alowing class assingment.
来源:https://stackoverflow.com/questions/24923749/python-self-vs-typeself-and-the-proper-use-of-class-variables