Python Classes: Attributes & Methods Explained
A Python class is a blueprint for creating objects with both data (attributes) and behavior (methods). This guide teaches you to define instance attributes (unique per object), class attributes (shared across all objects), and instance methods (functions that operate on an object's state). Understanding these fundamentals is essential for writing clean, maintainable object-oriented Python code.
Instance Attributes vs. Class Attributes: Understanding Data Organization
Attributes are variables associated with a class or its objects. Python supports two types of attributes with different scopes and lifetimes.
Instance Attributes: Unique Data Per Object
An instance attribute is a variable belonging to a specific object. Each object gets its own independent copy of instance attributes, so changes in one object do not affect other objects. Instance attributes are defined inside the __init__() constructor method using self.attribute_name = value.
class Car:
def __init__(self, make, model, year):
# These are INSTANCE attributes
self.make = make
self.model = model
self.year = year
car_one = Car("Toyota", "Camry", 2023)
car_two = Car("Honda", "Civic", 2022)
# Each object has its own attribute values
print(f"Car 1: {car_one.year} {car_one.make} {car_one.model}") # Output: Car 1: 2023 Toyota Camry
print(f"Car 2: {car_two.year} {car_two.make} {car_two.model}") # Output: Car 2: 2022 Honda Civic
# Modifying one object's attribute does not affect the other
car_one.year = 2024
print(car_two.year) # Output: 2022 (unchanged)
Instance attributes answer the question: "What data is specific to this object?" They form the object's state and are accessed using object.attribute_name.
Class Attributes: Shared Data Across All Instances
A class attribute is a variable that is shared by all instances of a class. It belongs to the class itself, not to any individual object. Class attributes are defined directly in the class body, outside any method, and remain constant across all instances unless explicitly modified on the class.
class Car:
# This is a CLASS attribute (shared by all Car instances)
wheels = 4
manufacturer_country = "Various"
def __init__(self, make, model):
# These are INSTANCE attributes
self.make = make
self.model = model
car_one = Car("Toyota", "Camry")
car_two = Car("Honda", "Civic")
# Both objects share the same class attribute
print(f"Car 1 has {car_one.wheels} wheels") # Output: Car 1 has 4 wheels
print(f"Car 2 has {car_two.wheels} wheels") # Output: Car 2 has 4 wheels
# Access class attributes directly from the class
print(f"Cars have {Car.wheels} wheels") # Output: Cars have 4 wheels
When to Use Each Type
Use instance attributes for data unique to each object: name, ID, status, configuration, current state. Use class attributes for constants or defaults shared across all objects: a species name for all animals, a number of wheels for all cars, or a default timeout value for all API clients.
Instance Methods: Adding Behavior to Objects
An instance method is a function defined inside a class that operates on an object's data. Methods allow objects to perform actions and encapsulate behavior with data. Every instance method has self as its first parameter, which refers to the specific object the method is called on.
The Self Parameter: Connecting Method to Object
When you call car.start_engine(), Python automatically passes the car object as the first argument (self) to the method. This binding connects the method to the specific object.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
# This is an INSTANCE METHOD
def start_engine(self):
"""Starts the car's engine."""
print(f"The {self.make} {self.model}'s engine is now running.")
# Another INSTANCE METHOD that returns a value
def describe(self) -> str:
"""Returns a description of the car."""
return f"{self.make} {self.model}"
my_car = Car("Tesla", "Model 3")
my_car.start_engine() # Output: The Tesla Model 3's engine is now running.
description = my_car.describe()
print(description) # Output: Tesla Model 3
Methods Accessing and Modifying Instance Attributes
Methods are most powerful when they read and modify an object's instance attributes:
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder
self.balance = initial_balance
def deposit(self, amount) -> None:
"""Adds funds to the account."""
if amount > 0:
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount) -> bool:
"""Removes funds from the account."""
if amount <= 0:
print("Withdrawal amount must be positive.")
return False
if amount > self.balance:
print(f"Insufficient funds. Balance: ${self.balance}")
return False
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
return True
def get_balance(self) -> float:
"""Returns the current balance."""
return self.balance
account = BankAccount("Alice", 1000)
account.deposit(500) # Output: Deposited $500. New balance: $1500
account.withdraw(200) # Output: Withdrew $200. New balance: $1300
print(account.get_balance()) # Output: 1300
In this example, each method reads self.account_holder and self.balance and may modify self.balance. The self parameter gives each method access to the object's current state.
How Self Works: The Automatic Binding Mechanism
When you call a method, Python performs automatic binding:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
"""Makes the dog bark."""
print(f"{self.name} says: Woof!")
my_dog = Dog("Buddy")
# These two calls are equivalent:
my_dog.bark() # Python passes my_dog as 'self' automatically
Dog.bark(my_dog) # Explicit passing (rarely used, but shows what happens)
Both print "Buddy says: Woof!". The dot notation (my_dog.bark()) automatically binds my_dog to self. Without this mechanism, methods would have no way to know which object they are operating on, making object-oriented programming impossible.
Practical Example: Building a Complete Class
Here is a practical example combining instance attributes, class attributes, and multiple methods:
class Book:
# CLASS attribute: all books are made of paper (a simplified assumption)
format_type = "Physical Book"
def __init__(self, title, author, pages):
# INSTANCE attributes
self.title = title
self.author = author
self.pages = pages
self.current_page = 0
def read_pages(self, num_pages) -> bool:
"""Advances the reading position."""
if self.current_page + num_pages > self.pages:
print(f"Cannot read {num_pages} pages. Book only has {self.pages} pages.")
return False
self.current_page += num_pages
print(f"Read {num_pages} pages. Now on page {self.current_page}.")
return True
def get_progress(self) -> float:
"""Returns reading progress as a percentage."""
return (self.current_page / self.pages) * 100
def reset(self) -> None:
"""Resets the book to the beginning."""
self.current_page = 0
print(f"Reset '{self.title}' to the beginning.")
book = Book("1984", "George Orwell", 328)
book.read_pages(50)
print(f"Progress: {book.get_progress():.1f}%") # Output: Progress: 15.2%
print(f"Format: {book.format_type}") # Output: Format: Physical Book
book.reset()
Key Takeaways
- Instance Attributes store unique data for each object. Define them in
__init__()usingself.name = value. Each object has independent copies. - Class Attributes store data shared across all instances. Define them in the class body outside methods. Modify carefully to avoid unintended side effects.
- Instance Methods are functions that operate on an object's state. Always include
selfas the first parameter. Call them usingobject.method(). - Self is the Key: The
selfparameter binds the method to a specific object, allowing the method to access and modify that object's attributes. - Encapsulation: Methods and attributes together encapsulate an object's state and behavior, which is the core principle of object-oriented programming.
- Readability: Always use descriptive method names and instance attribute names. Add docstrings to methods explaining their purpose and return values.
Frequently Asked Questions
What is the difference between a class and an instance?
A class is a blueprint (a template). An instance is a concrete object created from that blueprint. Think of a class as a cookie cutter and an instance as the actual cookie made from it. You define a class once, but you can create many instances (objects) from it.
Can I define instance attributes outside __init__()?
Technically yes, but do not do it. If you assign to self.new_attr in another method, Python creates that attribute at that moment. However, this makes the code harder to understand because attribute creation is scattered throughout methods. Always initialize all expected attributes in __init__() so readers know what attributes an object has.
Can methods call other methods on the same object?
Yes. Use self.other_method() to call another method from within a method:
class Example:
def method_a(self):
return "A"
def method_b(self):
return self.method_a() + " and B"
What happens if I forget the self parameter?
Python will raise an error when you call the method on an object. If you define def bark(self): but forget self, Python will not recognize it as a method, and calling dog.bark() will fail. Every instance method must have self.
Can class attributes be modified from an instance method?
Yes, but it affects all instances. Access the class attribute via the class name to modify it from a method: ClassName.class_attribute = new_value. Modifying it via self.class_attribute = new_value creates a new instance attribute that shadows the class attribute.
How do I call a method from another method in the same class?
Use self.method_name(). This calls the method on the current object:
class Example:
def method_a(self):
print("Method A")
def method_b(self):
self.method_a() # Calls method_a on the same object