Object-Oriented Programming (OOP) in Python
Python is a versatile programming language that supports various programming styles, including object-oriented programming (OOP) through the use of objects and classes.
An object is any entity that has attributes and behaviors. For example, a person is an object. It has
attributes - name, age, gender, etc.
behavior - coding, gaming, etc.
Similarly, a class is a blueprint for that object.
1. Basic Class and Object
Problem: Create a Car class with attributes like brand and model. Then create an instance of this class.
In Python, a class is defined using the class keyword. A class can have attributes (variables) and methods (functions). An object is an instance of a class. Let's create a Car class with attributes brand and model, and then create an instance of this class.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla")
2. Class Method and Self
Problem: Add a method to the Car class that displays the full name of the car (brand and model).
A class method is a method that is bound to a class rather than its object. The self parameter is a reference to the current instance of the class. Let's add a method to the Car class that displays the full name of the car (brand and model).
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def full_name(self):
return f"{self.brand} {self.model}"
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla")
print(my_car.full_name()) # Output: Toyota Corolla
3. Inheritance
Problem: Create an ElectricCar class that inherits from the Car class and has an additional attribute battery_size.
Inheritance is a way to form new classes using classes that have already been defined. The new class is called a derived class or child class, and the class that it inherits from is called the base class or parent class. Let's create an ElectricCar class that inherits from the Car class and has an additional attribute battery_size.
class ElectricCar(Car):
def __init__(self, brand, model, battery_size):
super().__init__(brand, model)
self.battery_size = battery_size
# Creating an instance of the ElectricCar class
my_electric_car = ElectricCar("Tesla", "Model S", "100 kWh")
4. Encapsulation
Problem: Modify the Car class to encapsulate the brand attribute, making it private, and provide a getter method for it.
Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit (class). In Python, encapsulation can be achieved using private attributes and getter and setter methods. Let's modify the Car class to encapsulate the brand attribute, making it private, and provide a getter method for it.
class Car:
def __init__(self, brand, model):
self.__brand = brand
self.model = model
def get_brand(self):
return self.__brand
def set_brand(self, new_brand):
self.__brand = new_brand
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla")
print(my_car.get_brand()) # Output: Toyota
my_car.set_brand("Honda")
print(my_car.get_brand()) # Output: Honda
5. Polymorphism
Problem: Demonstrate polymorphism by defining a method fuel_type in both Car and ElectricCar classes, but with different behaviors.
Polymorphism is the ability to present the same interface for different data types. In Python, polymorphism can be achieved by defining a method with the same name in different classes, but with different implementations. Let's demonstrate polymorphism by defining a method fuel_type in both Car and ElectricCar classes, but with different behaviors.
class Car:
def fuel_type(self):
return "Petrol or Diesel"
class ElectricCar(Car):
def fuel_type(self):
return "Battery"
# Creating instances of the Car and ElectricCar classes
my_car = Car()
my_electric_car = ElectricCar()
print(my_car.fuel_type()) # Output: Petrol or Diesel
print(my_electric_car.fuel_type()) # Output: Battery
6. Class Variables
Problem: Add a class variable to Car that keeps track of the number of cars created.
Class variables are shared among all instances of a class. They are defined within the class but outside any methods. Let's add a class variable to the Car class that keeps track of the number of cars created.
class Car:
total_cars = 0
def __init__(self, brand, model):
self.brand = brand
self.model = model
Car.total_cars += 1
# Creating instances of the Car class
my_car1 = Car("Toyota", "Corolla")
my_car2 = Car("Honda", "Civic")
print(Car.total_cars) # Output: 2
7. Static Method
Problem: Add a static method to the Car class that returns a general description of a car.
A static method is a method that does not require access to an instance of the class. It is defined using the @staticmethod decorator. Let's add a static method to the Car class that returns a general description of a car.
class Car:
@staticmethod
def general_description():
return "A very nice car"
print(Car.general_description()) # Output: A very nice car
8. Property Decorators
Problem: Use a property decorator in the Car class to make the model attribute read-only.
Property decorators are used to define properties in a class. They allow us to define getter, setter, and deleter methods for a property. Let's use a property decorator in the Car class to make the model attribute read-only.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.__model = model
@property
def model(self):
return self.__model
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla")
print(my_car.model) # Output: Corolla
my_car.model = "Camry" # AttributeError: can't set attribute
9. Class Inheritance and isinstance() Function
Problem: Demonstrate the use of isinstance() to check if my_tesla is an instance of Car and ElectricCar.
The isinstance() function is used to check if an object is an instance of a class or a subclass of a class. Let's demonstrate the use of isinstance() to check if my_tesla is an instance of Car and ElectricCar.
class Car:
pass
class ElectricCar(Car):
pass
my_tesla = ElectricCar()
print(isinstance(my_tesla, Car)) # Output: True
print(isinstance(my_tesla, ElectricCar)) # Output: True
10. Multiple Inheritance
Problem: Create two classes Battery and Engine, and let the ElectricCar class inherit from both, demonstrating multiple inheritance.
Multiple inheritance is a feature of some object-oriented programming languages in which a class can inherit from more than one superclass. Let's create two classes Battery and Engine, and let the ElectricCar class inherit from both, demonstrating multiple inheritance.
class Battery:
def battery_info(self):
return "super cool battery"
class Engine:
def engine_info(self):
return "super hot engine"
class ElectricCar(Battery, Engine):
pass
my_electric_car = ElectricCar()
print(my_electric_car.battery_info()) # Output: super cool battery
print(my_electric_car.engine_info()) # Output: super hot engine
Meet you in the next article on Decorators in Python.