Search code examples
pythonclass-variables

What is the proper way to access python class variables?


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?


Solution

  • I would say that the proper way to get access to the variable is simply:

    a_instance.z  #instance variable 'z'
    A.z           #class variable 'z'
    

    No need for Func1 and Func2 here.


    As a side note, if you must write Func2, it seems like a classmethod might be appropriate:

    @classmethod
    def Func2(cls):
        return cls.z
    

    As a final note, which version you use within methods (self.z vs. A.z vs. cls.z with classmethod) really depends on how you want your API to behave. Do you want the user to be able to shadow A.z by setting an instance attribute z? If so, then use self.z. If you don't want that shadowing, you can use A.z. Does the method need self? If not, then it's probably a classmethod, etc.