102. Instance Variables vs Class Variables
1. Basic Example of Instance and Class Variables
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 Human2. Changing Instance and Class Variables
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)3. Class Variable Shared Across Instances
4. Class and Instance Variables with Same Name
5. Accessing Class Variables via Class and Instance
6. Modifying Instance Variable Without Affecting Class Variable
7. Instance Variables in Inherited Classes
8. Overriding Class Variables in Subclasses
9. Class Variable Affects All Instances
10. Instance Variable Default Value
Summary of Differences:
Last updated