Static Class Variables in Python

Last Updated On Saturday 15th Jan 2022

Static and Class Methods

	class Test(object):

    # regular instance method:
    def MyMethod(self):
        pass

    # class method:
    @classmethod
    def MyClassMethod(klass):
        pass

    # static method:
    @staticmethod
    def MyStaticMethod():
        pass
	

The first argument to MyMethod() is bound to the class instance object.

In contrast, the first argument to MyClassMethod() is bound to the class object itself.

For MyStaticMethod(), none of the arguments are bound, and having arguments at all is optional.

Static Variables

Creating Static Variable

  • If the value of a variable is not varied from object to object, such type of variables we have to declare with in the class directly but outside of methods. Such types of variables are called Static variables.
  • For total class only one copy of static variable will be created and shared by all objects of that class.
  • We can access static variables either by class name or by object reference. But recommended to use class name.

Python Class Variables

	class Test(object):
    i = 3  # This is a class attribute

x = Test()
x.i = 12   # Attempt to change the value of the class attribute using x instance
assert x.i == Test.i  # ERROR
assert Test.i == 3    # Test.i was not affected
assert x.i == 12      # x.i is a different object than Test.i
	

Accessing Static Variable

  • Inside constructor: by using either self or classname
  • Inside instance method: by using either self or classname
  • Inside class method: by using either cls variable or classname
  • Inside static method: by using classname
  • From outside of class: by using either object reference or classname

Deleting/Removing Static Variable

  • We can delete static variables from anywhere by using the following syntax del classname.variablename
  • But inside classmethod we can also use cls variable del cls.variablename

Instance Variable vs Static Variable

	class Test:
    x=10
    def __init__(self):
        self.y=20

t1=Test()
t2=Test()
print('t1:',t1.x,t1.y)
print('t2:',t2.x,t2.y)
Test.x=888
t1.y=999
print('t1:',t1.x,t1.y)
print('t2:',t2.x,t2.y)
	
	t1: 10 20
t2: 10 20
t1: 888 999
t2: 888 20