Python instance and class variables


In Python, instance variables and class variables are two types of variables that are used to store data in classes. Understanding the difference between these two is essential for effective object-oriented programming. Here's a detailed explanation:

Instance Variables

  • Definition: Instance variables are variables that are defined inside a class and are associated with individual instances (objects) of that class. Each instance can have its own unique values for these variables.

  • Creation: Instance variables are typically initialized in the __init__ method (the constructor) using the self keyword.

  • Scope: They are only accessible through the instance of the class.

  • Example:

class Dog: def __init__(self, name, age): self.name = name # Instance variable self.age = age # Instance variable # Creating instances dog1 = Dog("Buddy", 3) dog2 = Dog("Max", 5) print(dog1.name) # Output: Buddy print(dog2.name) # Output: Max

Class Variables

  • Definition: Class variables are variables that are shared among all instances of a class. They are defined within the class but outside of any instance methods. All instances of the class can access and modify these variables.

  • Creation: Class variables are defined directly inside the class body.

  • Scope: They are accessible through both the class name and instances of the class.

  • Example:

class Dog: species = "Canis lupus familiaris" # Class variable def __init__(self, name, age): self.name = name # Instance variable self.age = age # Instance variable # Creating instances dog1 = Dog("Buddy", 3) dog2 = Dog("Max", 5) print(dog1.species) # Output: Canis lupus familiaris print(dog2.species) # Output: Canis lupus familiaris # Accessing class variable using class name print(Dog.species) # Output: Canis lupus familiaris

Key Differences

FeatureInstance VariablesClass Variables
ScopeUnique to each instanceShared among all instances
CreationDefined in the __init__ methodDefined within the class body
AccessAccessed using selfAccessed using the class name or self
MemoryEach instance has its own copyOnly one copy exists for the class

Summary

  • Instance variables store data unique to each object, while class variables hold data that is shared across all instances of the class.
  • Understanding these two types of variables is crucial for managing state and behavior in an object-oriented design, allowing for greater flexibility and organization in your code.