102. Instance Variables vs Class Variables

1. Basic Example of Instance and Class Variables

Copy

class Person:
    species = "Human"  # Class variable

    def __init__(self, name, age):
        self.name = name  # Instance variable
        self.age = age    # Instance variable

person1 = Person("John", 25)
person2 = Person("Alice", 30)

print(person1.name, person1.species)  # Output: John Human
print(person2.name, person2.species)  # Output: Alice Human

Explanation: species is a class variable shared by all instances, while name and age are instance variables, specific to each instance.


2. Changing Instance and Class Variables

Copy

class Animal:
    species = "Mammal"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

animal1 = Animal("Lion")
animal2 = Animal("Elephant")

animal1.species = "Big Cat"  # Modifying instance variable

print(animal1.species)  # Output: Big Cat
print(animal2.species)  # Output: Mammal (unchanged)

Explanation: Modifying species for animal1 creates an instance variable specific to that object, not affecting other instances.


3. Class Variable Shared Across Instances

Copy

Explanation: The class variable wheels is shared by all instances of the class, and changing it affects all instances.


4. Class and Instance Variables with Same Name

Copy

Explanation: The instance variable type overrides the class variable type within the instance, but the class variable remains unchanged.


5. Accessing Class Variables via Class and Instance

Copy

Explanation: Both the class and instances can access class variables, but accessing them via an instance is allowed, though less recommended.


6. Modifying Instance Variable Without Affecting Class Variable

Copy

Explanation: Modifying the genre attribute for book1 only changes its instance variable and does not affect book2.


7. Instance Variables in Inherited Classes

Copy

Explanation: The inherited sound class variable is shared among all Lion instances, while the name and region are instance variables.


8. Overriding Class Variables in Subclasses

Copy

Explanation: Dog overrides the species class variable, and this change only applies to instances of Dog, not the parent Animal.


9. Class Variable Affects All Instances

Copy

Explanation: The class variable count is shared across all instances, so both counter1 and counter2 reflect the same value.


10. Instance Variable Default Value

Copy

Explanation: The position is an instance variable that can be modified independently for each instance.


Summary of Differences:

  • Instance Variables are specific to each object created from a class. They are set using self in the __init__ method.

  • Class Variables are shared across all instances of the class and are set directly in the class body, not using self.

Last updated