Python class variable vs instance variable
In Python, a class variable is a variable that is shared among all instances of a class. It is defined within the class, but outside of any method, and can be accessed using the class name or an instance of the class.
An instance variable, on the other hand, is a variable that is specific to an instance of a class. It is defined within the class, usually in the constructor method (__init__
) and can be accessed using the dot notation on an instance of the class.
For example, the following code defines a class called Person
with a class variable species
and an instance variable name
:
1class Person: 2 species = "Homo sapiens" 3 4 def __init__(self, name): 5 self.name = name
You can access the class variable using the class name:
1print(Person.species) # Output: Homo sapiens
You can also access the class variable using an instance of the class:
1person = Person("William") 2print(person.species) # Output: Homo sapiens
You can access the instance variable using the dot notation on an instance of the class:
1person = Person("William") 2print(person.name) # Output: William
It's important to note that, if you change the value of a class variable using an instance, the change will be reflected across all instances of the class.
1person1 = Person("William") 2person2 = Person("Jane") 3 4print(person1.species) # Output: Homo sapiens 5print(person1.name) # Output: William 6print(person2.species) # Output: Homo sapiens 7print(person2.name) # Output: Jane 8 9person1.species = "Human" 10 11print(person1.species) # Output: Human 12print(person1.name) # Output: William 13print(person2.species) # Output: Human 14print(person2.name) # Output: Jane
In Python, a class variable is a variable that is shared among all instances of a class and is defined within the class but outside of any method. An instance variable is a variable that is specific to an instance of a class, defined within the class and usually in the constructor method and can be accessed using the dot notation on an instance of the class. Understanding the difference between class variables and instance variables is important for creating reusable and maintainable code in Python.