Class Variables and Class Methods
Overview
Unlike instance variables, class variables are shared across all objects created from a class. You'll also explore class methods and see how they act on the class as a whole rather than individual objects, providing shared state and behavior.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Class variables: Understand what class variables are and how they're shared across all objects.
- Class vs instance: Learn the key differences between class variables and instance variables.
- Class methods: Discover how to create methods that work with the class itself.
- @classmethod decorator: Learn how to use the
@classmethoddecorator to create class methods.
Why This Matters
Class variables let you store data that's shared by all objects of a class - like a counter that tracks how many objects have been created, or default settings that apply to all instances. Class methods let you create alternative constructors or perform operations that work with the class itself, not individual objects. This is powerful for managing shared state and creating flexible object creation patterns!
Step 1: Understanding Class Variables
Class variables are defined at the class level and are shared by all instances of that class:
class Dog:
species = "Canis familiaris" # Class variable
def __init__(self, name):
self.name = name # Instance variable
dog1 = Dog("Buddy")
dog2 = Dog("Max")
# All dogs share the same species
print(dog1.species) # "Canis familiaris"
print(dog2.species) # "Canis familiaris"
print(Dog.species) # "Canis familiaris"
Define at Class Level
Class variables are defined directly inside the class, outside of any method. They're not prefixed with self - they belong to the class itself!
Shared by All Objects
All objects created from the class share the same class variable. Changing it for one object changes it for all objects!
Access via Class or Object
You can access class variables using either ClassName.variable or object.variable. Both work!
Key Concept: Class variables are like shared resources - imagine a classroom where all students share the same whiteboard (class variable), but each student has their own notebook (instance variable). Changes to the whiteboard affect everyone!
Mini Practice #1: Class Variables
Try It YourselfCreate a class with a class variable:
What happened? Both students share the same school class variable! Even though Alice and Bob are different objects with different names (instance variables), they both belong to "Python Academy" (class variable). This is shared data that applies to all objects!
Step 2: Class Variables vs Instance Variables
Understanding the difference is crucial:
class Counter:
count = 0 # Class variable (shared)
def __init__(self, name):
self.name = name # Instance variable (unique)
Counter.count += 1 # Increment shared counter
c1 = Counter("First")
c2 = Counter("Second")
c3 = Counter("Third")
print(c1.name) # "First" (unique)
print(c2.name) # "Second" (unique)
print(Counter.count) # 3 (shared - counts all objects!)
Instance Variables
Defined with self.variable in __init__. Each object has its own copy. Changing one doesn't affect others. Used for object-specific data.
Class Variables
Defined at class level without self. All objects share the same variable. Changing it affects all objects. Used for shared data or constants.
When to Use Each
Use instance variables for data that's unique to each object (name, age, balance). Use class variables for data that should be the same for all objects (species, default settings, counters, constants).
Step 3: Class Methods
Class methods are methods that work with the class itself, not individual objects. They use the @classmethod decorator:
class Person:
population = 0 # Class variable
def __init__(self, name):
self.name = name
Person.population += 1
@classmethod
def get_population(cls):
return cls.population
@classmethod
def create_baby(cls, name):
return cls(name)
p1 = Person("Alice")
p2 = Person("Bob")
print(Person.get_population()) # 2
@classmethod Decorator
Use @classmethod before a method definition. This tells Python it's a class method, not an instance method.
cls Parameter
Class methods take cls (the class itself) as the first parameter instead of self. cls refers to the class!
Call via Class
Call class methods using ClassName.method() or object.method(). They work with the class, not individual objects!
Mini Practice #2: Class Methods
Try It YourselfCreate a class with a class method:
What happened? The get_total() class method accesses the class variable total_books using cls. It returns the total count of all Book objects created. Class methods are perfect for operations that work with the class as a whole!
Step 4: Alternative Constructors
Class methods are often used to create alternative ways to construct objects:
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_string):
year, month, day = date_string.split("-")
return cls(int(year), int(month), int(day))
# Two ways to create dates
date1 = Date(2024, 1, 15)
date2 = Date.from_string("2024-01-15") # Alternative constructor
Remember: Class methods let you create objects in different ways while keeping the class organized. They're especially useful when you want to parse data or create objects from different input formats!
End-of-Lesson Exercises
Exercise 1: Class Variable
Create a Car class with a class variable wheels = 4. Add an instance variable brand in __init__. Create two Car objects and print both the brand (instance) and wheels (class) for each.
Define class Car with wheels class variable, add __init__ with self.brand, create objects, print both attributes.
Exercise 2: Class Method
Create a Counter class with a class variable count = 0. Increment it in __init__. Add a class method get_count(cls) that returns the count. Create 3 Counter objects and print the total count.
Define class Counter with count class variable, increment in __init__, add @classmethod get_count, create 3 objects, print count.