Classes and Objects in Python
Defining a Class
A class is defined using the class
keyword followed by the class name and a colon. Inside the class, you can define methods (functions) and attributes (variables).
class Car:
# Class attribute
wheels = 4
# Initializer / Instance attributes
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Instance method
def description(self):
return f"{self.year} {self.make} {self.model}"
# Another instance method
def start_engine(self):
return f"The engine of {self.make} {self.model} is now running!"
Creating Objects
Objects are instances of a class. You create an object by calling the class name followed by parentheses.
# Creating instances of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2019)
# Accessing attributes and methods
print(car1.description()) # Output: 2020 Toyota Corolla
print(car2.start_engine()) # Output: The engine of Honda Civic is now running!
# Accessing class attribute
print(f"All cars have {car1.wheels} wheels.") # Output: All cars have 4 wheels.
Detailed Example
Let’s create a more detailed example to demonstrate additional concepts like inheritance, method overriding, and special methods.
Defining a Base Class and a Derived Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the initializer of the base class
self.breed = breed
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # Call the initializer of the base class
self.color = color
def speak(self):
return f"{self.name} says Meow!"
Creating Objects and Using Inheritance
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Tabby")
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
Inheritance
Imagine you’re building a restaurant management system using Python’s object-oriented programming features. Here’s how inheritance can help:
Base Class – MenuItem
:
class MenuItem:
def __init__(self, name, price):
self.name = name
self.price = price
def get_details(self):
return f"{self.name} - ${self.price}"
This base class represents a generic menu item with attributes name
and price
and a method get_details
that returns a formatted string description.
Derived Class – Beverage
(Inheriting from MenuItem
):
class Beverage(MenuItem):
def __init__(self, name, price, size):
super().__init__(name, price) # Call base class constructor
self.size = size
def get_details(self): # Override base class method
return f"{self.size} {self.name} - ${self.price}"
Beverage
inherits fromMenuItem
.- It adds an additional attribute
size
and overrides theget_details
method to include the size information. super().__init__(name, price)
calls the constructor of the base class to initialize the inherited attributes.
Derived Class – Food
(Inheriting from MenuItem
):
class Food(MenuItem):
def __init__(self, name, price, vegetarian):
super().__init__(name, price) # Call base class constructor
self.vegetarian = vegetarian
def is_vegetarian(self):
return self.vegetarian
def get_details(self): # Override base class method
veg_info = "Vegetarian" if self.vegetarian else "Non-Vegetarian"
return f"{self.name} ({veg_info}) - ${self.price}"
Food
inherits fromMenuItem
.- It adds an additional attribute
vegetarian
and a methodis_vegetarian
to check the dietary category. - It overrides the
get_details
method to include vegetarian information.
Using the Classes:
coffee = Beverage("Coffee", 2.5, "Small")
pizza = Food("Margherita Pizza", 12.99, False)
salad = Food("Greek Salad", 8.50, True)
print(coffee.get_details()) # Output: Small Coffee - $2.5
print(pizza.get_details()) # Output: Margherita Pizza (Non-Vegetarian) - $12.99
print(salad.is_vegetarian()) # Output: True
Benefits of Inheritance:
- Code Reuse: We reuse the functionalities (attributes and methods) of
MenuItem
inBeverage
andFood
, reducing code redundancy. - Polymorphism: Each derived class can customize the
get_details
method to present information specific to its type (beverage size, food type). - Extensibility: We can easily create new types of menu items (e.g.,
Dessert
) by inheriting fromMenuItem
and adding specific attributes and methods.
Special Methods
Special methods in Python are defined with double underscores before and after their names (e.g., __init__
). These methods enable you to define behaviors for built-in operations.
Example of Special Methods
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(5, 7)
v3 = v1 + v2
print(v3) # Output: Vector(7, 10)
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.