Class or Static Variables in Python?


When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.

Class or static variable are quite distinct from and does not conflict with any other member variable with the same name. Below is a program to demonstrate the use of class or static variable −

Example

class Fruits(object):
count = 0
def __init__(self, name, count):
self.name = name
self.count = count
Fruits.count = Fruits.count + count

def main():
apples = Fruits("apples", 3);
pears = Fruits("pears", 4);
print (apples.count)
print (pears.count)
print (Fruits.count)
print (apples.__class__.count) # This is Fruit.count
print (type(pears).count) # So is this

if __name__ == '__main__':
main()

Result

3
4
7
7
7

Another example to demonstrate the use of variable defined on the class level −

Example

class example:
staticVariable = 9 # Access through class

print (example.staticVariable) # Gives 9

#Access through an instance
instance = example()
print(instance.staticVariable) #Again gives 9

#Change within an instance
instance.staticVariable = 12
print(instance.staticVariable) # Gives 12
print(example.staticVariable) #Gives 9

output

9
9
12
9

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements