- Defined directly inside the class definition
- Shared by all instances of the class
- The same value is accessible from all instances
- Changing it affects all instances
- Defined inside methods (typically
__init__
) - Unique to each instance
- Each instance can have different values
- Changing one instance doesn't affect others
class Dog:
# Class attribute
species = "Canis familiaris"
count = 0 # Tracks how many dogs we've created
def __init__(self, name, age):
# Instance attributes
self.name = name
self.age = age
Dog.count += 1 # Increment the class attribute
def description(self):
return f"{self.name} is {self.age} years old"
def speak(self, sound):
return f"{self.name} says {sound}"
# Create instances
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
# Access class attribute (same for all instances)
print(buddy.species) # Canis familiaris
print(miles.species) # Canis familiaris
print(Dog.species) # Canis familiaris
# Access instance attributes (unique to each instance)
print(buddy.name) # Buddy
print(miles.name) # Miles
# Modify instance attribute (only affects one instance)
buddy.age = 10
print(buddy.age) # 10
print(miles.age) # 4 (unchanged)
# Modify class attribute (affects all instances)
Dog.species = "Canis lupus"
print(buddy.species) # Canis lupus
print(miles.species) # Canis lupus
# Class attribute tracking instances
print(f"Total dogs created: {Dog.count}") # 2
# You can also add instance attributes dynamically
buddy.breed = "Golden Retriever"
print(buddy.breed) # Golden Retriever
# print(miles.breed) # AttributeError (only buddy has this)
- Scope: Class attributes belong to the class, instance attributes belong to objects
- Memory: Class attributes are stored once per class, instance attributes per object
- Access: Class attributes can be accessed through class or instance, instance only through instance
- Modification: Changing class attribute affects all instances, instance only affects one
Class attributes are often used for:
- Constants/defaults shared by all instances
- Tracking class-wide data (like counting instances)
- Configuration values that should be consistent across instances