Previous Index Next

Class Variables

Variables declared inside the class definition, but not inside a method are class variables. The class variable has only one copy in memory and is shared by all objects of a class. In other words, a class variable represents the property of the class, not of a specific object of the class. A class variable can be accessed through any objects of that class. A class variable also exists even when no object of that class exists.

class Dog:
 
    kind = 'canine'     # class variable shared by all instances

    def __init__(self, name):
        self.name = name # instance variable unique to each instance

d = Dog('Fido')
e = Dog('Buddy')
print(d.kind)            # shared by all dogs
print(e.kind)            # shared by all dogs
print(d.name)            # unique to d
print(e.name)            # unique to e

Output

canine
canine
Fido
Buddy

Previous Index Next