Having a class
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
Both methods (Func1
and Func2
) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address z
.
The result of Func*
would only differ if an instance would shadow z
with something like self.z = None
.
What is the proper python way to access the class variable z
using the syntax of Func1
or Func2
?
I would usually use
self.z
, because in case there are subclasses with different values forz
it will choose the "right" one. The only reason not to do that is if you know you will always want theA
version notwithstanding.Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creating of mixin classes.
If you don't care about value clobbering and things like that, you're fine with
self.z
. Otherwise,A.z
will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclassB
redefinesz
but notFunc2
:Which is quite logical, after all. So, if you want to access a class variable in a, somehow, polymorphic way, you can just do one of the following:
According to the documentation, the second form does not work with old-style classes, so the first form is usually more comptaible across Python 2.x versions. However, the second form is the safest one for new-style classes and, thus, for Python 3.x, as classes may redefine the
__class__
attribute.I would say that the proper way to get access to the variable is simply:
No need for
Func1
andFunc2
here.As a side note, if you must write
Func2
, it seems like aclassmethod
might be appropriate:As a final note, which version you use within methods (
self.z
vs.A.z
vs.cls.z
withclassmethod
) really depends on how you want your API to behave. Do you want the user to be able to shadowA.z
by setting an instance attributez
? If so, then useself.z
. If you don't want that shadowing, you can useA.z
. Does the method needself
? If not, then it's probably a classmethod, etc.