Python Classes and Objects

Classes and objects are fundamental building blocks of Object-Oriented Programming (OOP). In Python, a class acts as a blueprint for creating objects, and an object is an instance of a class. This tutorial will explain how to create and use classes and objects in Python with examples.

What is a Class?

A class is a user-defined data type that acts as a blueprint for creating objects. It can contain attributes (data) and methods (functions).

# Syntax to define a class
class ClassName:
    # Constructor method
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    # Method
    def method_name(self):
        return f"Attribute 1: {self.attribute1}, Attribute 2: {self.attribute2}"

Try It Now

What is an Object?

An object is an instance of a class. Objects store data in attributes and use methods to perform actions.

Example: Creating a Class and an Object

Let’s define a simple class and create an object from it.

# Define a class
class Person:
    def __init__(self, name, age):
        self.name = name  # Attribute
        self.age = age    # Attribute

    def introduce(self):  # Method
        return f"My name is {self.name} and I am {self.age} years old."

# Create an object (instance) of the class
person1 = Person("Alice", 25)

# Access attributes and methods
print(person1.name)  # Output: Alice
print(person1.introduce())  # Output: My name is Alice and I am 25 years old.

Try It Now

The __init__() Method

The __init__() method is a special method called the constructor. It initializes the object’s attributes when the object is created.

Example:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def details(self):
        return f"Car: {self.brand} {self.model}"

car1 = Car("Toyota", "Corolla")
print(car1.details())  # Output: Car: Toyota Corolla

Try It Now

Instance vs. Class Attributes

Attributes can either be specific to an instance or shared among all instances.

Example:

class Employee:
    company = "TechCorp"  # Class attribute

    def __init__(self, name, salary):
        self.name = name  # Instance attribute
        self.salary = salary

# Create objects
emp1 = Employee("John", 50000)
emp2 = Employee("Jane", 60000)

# Access attributes
print(emp1.company)  # Output: TechCorp
print(emp2.name)     # Output: Jane

Try It Now

Adding Methods to a Class

Methods are functions defined within a class that operate on its attributes.

Example:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

    def circumference(self):
        return 2 * 3.14 * self.radius

circle1 = Circle(5)
print(f"Area: {circle1.area()}")           # Output: Area: 78.5
print(f"Circumference: {circle1.circumference()}")  # Output: Circumference: 31.4

Try It Now

Updating Attributes

Attributes of an object can be updated directly.

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

# Create an object
student1 = Student("Tom", "A")

# Update an attribute
student1.grade = "A+"
print(student1.grade)  # Output: A+

Try It Now

Deleting Attributes

You can delete an attribute using the del keyword.

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

book1 = Book("1984", "George Orwell")

# Delete the title attribute
del book1.title

# Accessing deleted attribute will raise an error
# print(book1.title)  # AttributeError

Try It Now

Class Methods and Static Methods

In addition to instance methods, classes can have class methods and static methods.

  • Class methods: Use the @classmethod decorator and operate on class attributes.
  • Static methods: Use the @staticmethod decorator and do not access instance or class attributes.

Example:

class Math:
    @staticmethod
    def add(a, b):
        return a + b

    @classmethod
    def multiply(cls, a, b):
        return a * b

print(Math.add(5, 10))        # Output: 15
print(Math.multiply(5, 10))   # Output: 50

Try It Now

Conclusion

Understanding classes and objects is essential for writing efficient and modular Python code. By using classes, you can model real-world entities, manage data, and create reusable code.