Python Classes
In Python, classes are a way to bundle data and functionality together. Creating a class allows you to define the structure and behavior of objects. Think of a class like a blueprint for an object. If you're familiar with real-world concepts like cars, think of a class as a blueprint for a car, and each car object can have its own specific attributes (like color, model, etc.) and methods (like drive, stop, etc.).
Here's what you'll learn about Python classes:
- Creating a class: How to define a class in Python.
- Attributes and methods: How to define and use variables (attributes) and functions (methods) within a class.
- Instances of a class: How to create objects (instances) from a class and use them.
- Constructor (`__init__`): How to initialize objects with specific values when they're created.
What You'll Learn
You will learn the basics of defining and using classes in Python. We'll cover the fundamental concepts of object-oriented programming (OOP), such as attributes, methods, and instances.
Creating a Class in Python
In Python, you can create a class by using the class keyword followed by the name of the class. The class body contains attributes and methods that define the behavior and properties of the objects created from that class. Let's go through the steps of creating a basic class in Python.
Basic Syntax of a Python Class
Here’s the basic syntax to define a class in Python:
class ClassName:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
def some_method(self):
# method logic here
pass
class ClassName:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
def some_method(self):
# method logic here
pass
Let's break this down:
- class ClassName: This defines the class name, which follows the convention of using CamelCase for class names.
- def __init__(self, ...): This is the constructor method. It’s automatically called when a new object of the class is created. The self parameter refers to the current instance (object) of the class, and it’s used to access attributes and methods inside the class.
- self.parameter1 = parameter1: Here, we're defining the class attributes. These attributes will be set when an object is created from the class.
- def some_method(self): This is a regular method inside the class that can operate on class attributes or perform any other actions.
Understanding the Constructor Method: __init__
In Python, the __init__ method is a special method known as the constructor. It's automatically called when a new object is created from a class. This method is typically used to initialize instance variables and prepare the object for use.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance of the Person class
person1 = Person("Alice", 30)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance of the Person class
person1 = Person("Alice", 30)
In this example:
- The __init__ method is defined inside the Person class and takes self, name, and age as parameters.
- The self parameter refers to the instance of the class being created. It allows you to assign values to the object's attributes and access other methods within the class.
- self.name and self.age are instance variables initialized when a new object is created.
- When person1 is created, the constructor automatically assigns the name "Alice" and age 30 to that instance.
Creating an Instance (Object) of a Class
Once the class is defined, you can create an instance (object) of the class by calling the class name with the required parameters.
# Create an instance of the class
my_object = ClassName("value1", "value2")
# Create an instance of the class
my_object = ClassName("value1", "value2")
Example: Creating a Simple Car Class
Here's a practical example where we create a class for a car. The class will have attributes like make, model, and year, and a method to display the car's information.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the method to display car info
my_car.display_info() #output 2025, xyz_maker, xyz_model
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the method to display car info
my_car.display_info() #output 2025, xyz_maker, xyz_model
In this example:
- The __init__ method initializes the car’s attributes (make, model, and year) when an instance is created.
- The display_info method is used to print out the details of the car.
- When we create an object my_car from the Car class and call display_info(), it prints: 2025 xyz_maker xyz_model.
Instantiating Multiple Objects
You can create as many instances as you need from the class. Each instance will have its own set of attributes.
# Create another car object
another_car = Car("abc_maker", "abc_model", 2025)
another_car.display_info() # Output: 2025 abc_maker abc_model
# Create another car object
another_car = Car("abc_maker", "abc_model", 2025)
another_car.display_info() # Output: 2025 abc_maker abc_model
In this case, we created a new object another_car with different attributes, and when we call display_info(), it prints the details of that particular car.
Attributes and Methods of a Class
In Python, classes can have two main components: attributes and methods. Attributes are the data associated with a class, while methods are functions that define the behavior of the class and operate on its attributes. Understanding the difference between instance attributes and class attributes, as well as how to define and use methods, is essential when working with object-oriented programming.
Instance Attributes
Instance attributes are specific to each object created from the class. These attributes are initialized in the __init__ method and are accessed using the self keyword. Each object of the class can have different values for its instance attributes.
Example: Instance Attributes
Let's modify our Car class to demonstrate instance attributes:
class Car:
def __init__(self, make, model, year):
self.make = make # instance attribute
self.model = model # instance attribute
self.year = year # instance attribute
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Accessing instance attributes
print(my_car.make) # Output: xyz_maker
print(my_car.model) # Output: xyz_model
class Car:
def __init__(self, make, model, year):
self.make = make # instance attribute
self.model = model # instance attribute
self.year = year # instance attribute
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Accessing instance attributes
print(my_car.make) # Output: xyz_maker
print(my_car.model) # Output: xyz_model
In this example:
- We created instance attributes make, model, and year inside the __init__ method using the self keyword.
- Each object created from the class will have its own values for these attributes. For example, my_car.make is "xyz_maker" and my_car.model is "xyz_model".
Class Attributes
Class attributes, unlike instance attributes, are shared among all instances of the class. They are defined outside of the __init__ method and are accessed using the class name or an instance. Class attributes are usually used for values that are constant for all instances of the class.
Example: Class Attributes
Here's an example of defining and using class attributes:
class Car:
wheels = 4 # class attribute
def __init__(self, make, model, year):
self.make = make # instance attribute
self.model = model # instance attribute
self.year = year # instance attribute
def display_info(self):
print(f"{self.year} {self.make} {self.model} with {Car.wheels} wheels")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Accessing class attribute using the class name
print(Car.wheels) # Output: 4
# Accessing class attribute using an instance
print(my_car.wheels) # Output: 4
class Car:
wheels = 4 # class attribute
def __init__(self, make, model, year):
self.make = make # instance attribute
self.model = model # instance attribute
self.year = year # instance attribute
def display_info(self):
print(f"{self.year} {self.make} {self.model} with {Car.wheels} wheels")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Accessing class attribute using the class name
print(Car.wheels) # Output: 4
# Accessing class attribute using an instance
print(my_car.wheels) # Output: 4
In this example:
- The class attribute wheels is shared across all instances of the Car class.
- We can access the class attribute either through the class name, Car.wheels, or through an instance, my_car.wheels.
- Each instance, such as my_car, will have the same value for the wheels attribute (which is 4 in this case).
Methods
Methods are functions defined within a class that describe the behaviors or actions that the objects of the class can perform. They can modify the object's attributes or perform any task related to the object. The first parameter of a method is always self, which refers to the instance of the object.
Example: Defining and Calling a Method
Let's extend our Car class by adding a method that changes the car's year:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
def update_year(self, new_year):
self.year = new_year
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Displaying the initial car info
my_car.display_info() # Output: 2025 xyz_maker xyz_model
# Using the update_year method to change the car's year
my_car.update_year(2023)
# Displaying the updated car info
my_car.display_info() # Output: 2023 xyz_maker xyz_model
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
def update_year(self, new_year):
self.year = new_year
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Displaying the initial car info
my_car.display_info() # Output: 2025 xyz_maker xyz_model
# Using the update_year method to change the car's year
my_car.update_year(2023)
# Displaying the updated car info
my_car.display_info() # Output: 2023 xyz_maker xyz_model
In this example:
- The method update_year takes a new year as a parameter and updates the year attribute of the car instance.
- We created an object my_car from the Car class, displayed its information, updated its year, and displayed the updated information again.
Class Methods and Static Methods
In addition to regular instance methods, Python also supports class methods and static methods:
- Class Methods: Defined using the @classmethod decorator. They take a cls parameter instead of self and can modify class attributes. They are called on the class itself, not on an instance.
Use case: Class methods are useful when you want to create factory methods, manage shared state across all instances, or update class-level data. - Static Methods: Defined using the @staticmethod decorator. They don't take self or cls as the first parameter. They are used for utility functions that don’t need access to instance or class attributes.
Use case: Static methods are best for helper functions related to the class but not dependent on class or instance data — for example, input validation or formatting operations.
Example: Class Method and Static Method
class Car:
wheels = 4
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
@classmethod
def set_wheels(cls, new_wheels):
cls.wheels = new_wheels
@staticmethod
def car_info():
print("Cars are essential for transportation.")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the class method to update the number of wheels
Car.set_wheels(6)
# Calling the static method
Car.car_info()
class Car:
wheels = 4
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
@classmethod
def set_wheels(cls, new_wheels):
cls.wheels = new_wheels
@staticmethod
def car_info():
print("Cars are essential for transportation.")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the class method to update the number of wheels
Car.set_wheels(6)
# Calling the static method
Car.car_info()
In this example:
- The set_wheels method is a class method that updates the class attribute wheels for all instances of the class.
- The car_info method is a static method, providing general information about cars without relying on any instance or class attributes.
Instances (Objects) of a Class
In Python, when you create an instance of a class, you are essentially creating an object that is based on the class blueprint. This object contains its own set of attributes (which can be different from other objects created from the same class) and has access to the methods defined in the class. The process of creating an object is called "instantiating" the class.
Creating an Instance (Object)
To create an instance of a class, you call the class as if it were a function. This triggers the __init__ method, which initializes the object's attributes. The syntax for creating an object is:
# Syntax to create an object
object_name = ClassName(arguments)
# Syntax to create an object
object_name = ClassName(arguments)
Let’s use the Car class to demonstrate how to create an instance (object) of a class.
Example: Creating an Object
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the display_info method on the object
my_car.display_info() # Output: 2025 xyz_maker xyz_model
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)
# Calling the display_info method on the object
my_car.display_info() # Output: 2025 xyz_maker xyz_model
In this example:
- The class Car defines the attributes make, model, and year, and a method display_info to display the car's details.
- We create an instance of the class by calling Car("xyz_maker", "xyz_model", 2025), which initializes the object my_car with the provided values for make, model, and year.
- We then call the display_info method to print out the car's details.
Accessing Attributes and Methods of an Object
After an object is created, we can access its attributes and methods using dot notation. The dot notation allows us to reference specific attributes or call methods on the object. Let’s see how to access the attributes and methods of an object.
Example: Accessing Object Attributes and Methods
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an object of the Car class
my_car = Car("abc_maker", "abc_model", 2022)
# Accessing object attributes
print(my_car.make) # Output: abc_maker
print(my_car.year) # Output: 2022
# Calling a method on the object
my_car.display_info() # Output: 2022 abc_maker abc_model
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating an object of the Car class
my_car = Car("abc_maker", "abc_model", 2022)
# Accessing object attributes
print(my_car.make) # Output: abc_maker
print(my_car.year) # Output: 2022
# Calling a method on the object
my_car.display_info() # Output: 2022 abc_maker abc_model
In this example:
- We created an object my_car using the Car class with attributes make, model, and year.
- We accessed the object's attributes directly, such as my_car.make and my_car.year.
- We also called the method display_info to print the car's information.
Multiple Instances of a Class
You can create multiple instances of a class, each with its own unique set of attributes. Every object created from the same class can have different values for its attributes, but they share the same methods. This allows for the creation of many objects with similar behavior but different data.
Example: Multiple Instances of a Class
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating multiple instances of the Car class
car1 = Car("Ford", "Mustang", 2020)
car2 = Car("Chevrolet", "Camaro", 2025)
# Calling methods on each instance
car1.display_info() # Output: 2020 Ford Mustang
car2.display_info() # Output: 2025 Chevrolet Camaro
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
# Creating multiple instances of the Car class
car1 = Car("Ford", "Mustang", 2020)
car2 = Car("Chevrolet", "Camaro", 2025)
# Calling methods on each instance
car1.display_info() # Output: 2020 Ford Mustang
car2.display_info() # Output: 2025 Chevrolet Camaro
In this example:
- We created two different instances of the Car class: car1 and car2.
- Each instance has its own unique values for make, model, and year, but they share the same method display_info to print the car's details.
Instance Variables vs. Class Variables in Python
While an instance variable holds data specific to an object, a class variable holds data that is shared among all instances of the class. It is important to understand the difference when creating and accessing attributes. Let’s review this concept with an example:
Example: Instance Variables vs. Class Variables
class Car:
wheels = 4 # class variable (shared among all instances)
def __init__(self, make, model, year):
self.make = make # instance variable
self.model = model # instance variable
self.year = year # instance variable
def display_info(self):
print(f"{self.year} {self.make} {self.model} with {Car.wheels} wheels")
# Creating two instances of the Car class
car1 = Car("xyz_maker", "xyz_model", 2020)
car2 = Car("abc_maker", "abc_model", 2025)
# Accessing the instance variable
print(car1.make) # Output: xyz_maker
print(car2.make) # Output: abc_maker
# Accessing the class variable (shared between instances)
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
class Car:
wheels = 4 # class variable (shared among all instances)
def __init__(self, make, model, year):
self.make = make # instance variable
self.model = model # instance variable
self.year = year # instance variable
def display_info(self):
print(f"{self.year} {self.make} {self.model} with {Car.wheels} wheels")
# Creating two instances of the Car class
car1 = Car("xyz_maker", "xyz_model", 2020)
car2 = Car("abc_maker", "abc_model", 2025)
# Accessing the instance variable
print(car1.make) # Output: xyz_maker
print(car2.make) # Output: abc_maker
# Accessing the class variable (shared between instances)
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
In this example:
- Each object has its own instance variables: make, model, and year.
- The class variable wheels is shared among all instances of the class.
- Even though we created two instances, both car1 and car2 share the same value for wheels because it's a class variable.
Frequently Asked Questions
What is a class in Python?
What is a class in Python?
A class in Python is a blueprint for creating objects. It defines the attributes (variables) and methods (functions) that objects of the class can have.
How do I define a class in Python?
How do I define a class in Python?
To define a class in Python, use the `class` keyword followed by the class name. The body of the class contains its methods and attributes, typically indented.
What is the difference between a class and an object in Python?
What is the difference between a class and an object in Python?
A class is a blueprint for creating objects, while an object is an instance of a class. A class defines the structure and behavior, and objects represent specific data following that structure.
What is inheritance in Python classes?
What is inheritance in Python classes?
Inheritance allows a new class to inherit attributes and methods from an existing class, promoting code reuse and building hierarchical relationships between classes.
Can I have multiple constructors in a Python class?
Can I have multiple constructors in a Python class?
Python does not support method overloading directly, but you can use default arguments or variable-length argument lists in the constructor (`__init__`) method to simulate multiple constructors.
What's Next?
Next, you'll explore Python objects—how they are created, how they work behind the scenes, and how they interact with classes. Understanding objects is key to mastering object-oriented programming in Python.