timerring

Python Object Oriented Programming

December 23, 2024 · 5 min read · Page View:
Tutorial
Python
If you have any questions, feel free to comment below. And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

This article will review the object-oriented programming of Python. Mainly about the class, inheritance, and polymorphism.

CH6 Class #

Introduction #

  • Everything is an object
  • Everything has its own attributes
  • Everything has its own methods

Class is the carrier of objects

Each cat is an object, we can abstract the common features of a class of objects, and create a generic class.

# Create a class
class Cat():
    """Simulate a cat"""

    def __init__(self, name):
        """Initialize the attributes"""
        self.name = name
    
    def jump(self):
        """Simulate a cat jumping"""
        print(self.name + " is jumping") 

my_cat = Cat("Loser")
your_cat = Cat("Lucky")

print(my_cat.name) # Loser
print(your_cat.name) # Lucky
# Call method
my_cat.jump() # Loser is jumping
your_cat.jump() # Lucky is jumping

Define a class #

Three elements: class name, attributes, methods

Class naming #

  • Camel case - the first letter of each word is capitalized
  • Leave two blank lines before the “class” and leave two blank lines after the class

Class attributes #

class Car():
    """Simulate a car"""
    # def __init__(self, the parameters to be passed)
    def __init__(self, brand, model, year):
        """Initialize the attributes of the car"""
        self.brand = brand
        self.model = model
        self.year = year
        self.mileage = 0

Class methods #

A function defined inside a class

class Car():
    """Simulate a car"""
    
    def __init__(self, brand, model, year):
        """Initialize the attributes of the car"""
        self.brand = brand
        self.model = model
        self.year = year
        self.mileage = 0
        
    def get_main_information(self): # you cannot omit self
        """Get the main information of the car"""
        print("Brand: {}    Model: {}    Year: {}".format(self.brand, self.model, self.year))
    
    def get_mileage(self):
        """Get the mileage of the car"""
        return "Mileage: {} km".format(self.mileage)

Create an instance #

Assign the instance to an object, and pass the corresponding parameters during instantiation.

my_new_car = Car("Audi", "A6", 2018)

Access attributes #

Instance name.attribute name

print(my_new_car.brand) # Audi
print(my_new_car.model) # A6
print(my_new_car.year) # 2018

Call methods #

Instance name.method name(necessary parameters)

my_new_car = Car("Audi", "A6", 2018)
my_new_car.get_main_information() # Brand: Audi    Model: A6    Year: 2018

Modify attributes #

Direct modification #

First access, then modify

my_old_car.mileage = 12000
print(my_old_car.mileage) # 12000

Modify attributes through methods #

class Car():
    """Simulate a car"""
    
    def __init__(self, brand, model, year):
        """Initialize the attributes of the car"""
        self.brand = brand
        self.model = model
        self.year = year
        self.mileage = 0
        
    def get_main_information(self): # self cannot be omitted
        """Get the main information of the car"""
        print("Brand: {}    Model: {}    Year: {}".format(self.brand, self.model, self.year))
    
    def set_mileage(self, distance):
        """Set the mileage of the car"""
        self.mileage = distance

my_old_car.set_mileage(8000)

You can create an infinite number of instances

my_new_car = Car("Audi", "A6", 2018)
my_cars = [my_new_car, my_old_car]

Inheritance of classes #

Inheritance is the process of low-level abstraction inheriting high-level abstraction

Simple inheritance #

Parent class

class Car():
    """Simulate a car"""
    
    def __init__(self, brand, model, year):
        """Initialize the attributes of the car"""
        self.brand = brand
        self.model = model
        self.year = year
        self.mileage = 0
        
        
    def get_main_information(self):        # self cannot be omitted
        """Get the main information of the car"""
        print("Brand: {}    Model: {}    Year: {}".format(self.brand, self.model, self.year))
    
    def get_mileage(self):
        """Get the mileage of the car"""
        print("Mileage: {} km".format(self.mileage)) 
    
    def set_mileage(self, distance):
        """Set the mileage of the car"""
        if distance >= 0:
            self.mileage = distance
        else:
            print("Mileage cannot be negative!")
    
    def increment_mileage(self, distance):
        """Accumulate the mileage"""
        if distance >= 0:
            self.mileage += distance
        else:
            print("The added mileage cannot be negative!")

Subclass

class Subclass name (Parent class name):

  • Create an electric car class
class ElectricCar(Car):
    """Simulate an electric car"""
    
    def __init__(self, brand, model, year):
        """Initialize the attributes of the electric car"""
        super().__init__(brand, model, year)  # Declare the inheritance of the parent class, super is the superclass (parent class)
  • Automatically inherit all methods from the parent class
my_electric_car = ElectricCar("NextWeek", "FF91", 2046)
my_electric_car.get_main_information() # Brand: NextWeek    Model: FF91    Year: 2046

Add attributes and methods to the subclass #

class ElectricCar(Car):
    """Simulate an electric car"""
    
    def __init__(self, brand, model, year, bettery_size):# New parameters: bettery_size
        """Initialize the attributes of the electric car"""
        super().__init__(brand, model, year)    # Declare the inheritance of the parent class
        self.bettery_size = bettery_size        # Battery capacity
        self.electric_quantity = bettery_size   # Battery remaining capacity
        self.electric2distance_ratio = 5        # Electric quantity distance conversion coefficient 5 km/kW.h
        self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage
    
    def get_electric_quantit(self):
        """Get the current battery capacity"""
        print("Current battery remaining capacity: {} kW.h".format(self.electric_quantity))
        
    def set_electric_quantity(self, electric_quantity):
        """Set the battery remaining capacity, recalculate the mileage that can be supported"""
        if electric_quantity >= 0 and electric_quantity <= self.bettery_size:
            self.electric_quantity = electric_quantity
            self.remainder_range = self.electric_quantity*self.electric2distance_ratio
        else:
            print("The battery remaining capacity is not set in a reasonable range!")
    
    def get_remainder_range(self):
        """Get the remaining mileage"""
        print("The current battery remaining capacity can continue driving {} km".format(self.remainder_range))              
my_electric_car = ElectricCar("NextWeek", "FF91", 2046, 70)
my_electric_car.get_electric_quantit() # Current battery remaining capacity: 70 kW.h
my_electric_car.get_remainder_range()  # The current battery remaining capacity can continue driving 350 km
my_electric_car.set_electric_quantity(50)  # Reset the battery remaining capacity
my_electric_car.get_electric_quantit() # Current battery remaining capacity: 50 kW.h
my_electric_car.get_remainder_range() # The current battery remaining capacity can continue driving 250 km

Overwrite the parent class method - Polymorphism #

First look for the method in the subclass, if not found, look for the method in the parent class. Therefore, the subclass can overwrite the parent class method.

class ElectricCar(Car):
    """Simulate an electric car"""
    
    def __init__(self, brand, model, year, bettery_size):
        """Initialize the attributes of the electric car"""
        super().__init__(brand, model, year)    # Declare the inheritance of the parent class
        self.bettery_size = bettery_size        # Battery capacity
        self.electric_quantity = bettery_size   # Battery remaining capacity
        self.electric2distance_ratio = 5        # Electric quantity distance conversion coefficient 5 km/kW.h
        self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage
    
    def get_main_information(self):        # Overwrite the parent class method
        """Get the main information of the car"""
        print("Brand: {}    Model: {}    Year: {}    Remaining mileage: {} km"
              .format(self.brand, self.model, self.year, self.bettery_size*self.electric2distance_ratio))


my_electric_car = ElectricCar("NextWeek", "FF91", 2046, 70)
my_electric_car.get_main_information() # Brand: NextWeek    Model: FF91    Year: 2046    Remaining mileage: 350 km

Using instances in classes #

Abstract the battery as an object.

class Bettery():
    """Simulate the battery of an electric car"""
    
    def __init__(self, bettery_size = 70):
        self.bettery_size = bettery_size        # Battery capacity
        self.electric_quantity = bettery_size   # Battery remaining capacity
        self.electric2distance_ratio = 5        # Electric quantity distance conversion coefficient 5 km/kW.h
        self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage

    def get_electric_quantit(self):
        """Get the current battery remaining capacity"""
        print("Current battery remaining capacity: {} kW.h".format(self.electric_quantity))
        
    def set_electric_quantity(self, electric_quantity):
        """Set the battery remaining capacity, recalculate the mileage that can be supported"""
        if electric_quantity >= 0 and electric_quantity <= self.bettery_size:
            self.electric_quantity = electric_quantity
            self.remainder_range = self.electric_quantity*self.electric2distance_ratio
        else:
            print("The battery remaining capacity is not set in a reasonable range!")
    
    def get_remainder_range(self):
        """Get the remaining mileage"""
        print("The current battery remaining capacity can continue driving {} km".format(self.remainder_range))
class ElectricCar(Car):
    """Simulate an electric car"""
    
    def __init__(self, brand, model, year, bettery_size):
        """Initialize the attributes of the electric car"""
        super().__init__(brand, model, year)    # Declare the inheritance of the parent class
        self.bettery = Bettery(bettery_size)    # Battery
    
    def get_main_information(self):        # Overwrite the parent class method
        """Get the main information of the car"""
        print("Brand: {}    Model: {}    Year: {}    Remaining mileage: {} km"
              .format(self.brand, self.model, self.year, 
              self.bettery.bettery_size*self.bettery.electric2distance_ratio))
my_electric_car = ElectricCar("NextWeek", "FF91", 2046, 70)
my_electric_car.get_main_information() # Brand: NextWeek    Model: FF91    Year: 2046    Remaining mileage: 350 km

my_electric_car.bettery.get_electric_quantit() # Current battery remaining capacity: 70 kW.h

my_electric_car.bettery.set_electric_quantity(50)       # Reset the battery remaining capacity
my_electric_car.bettery.get_electric_quantit()          # Current battery remaining capacity: 50 kW.h

my_electric_car.bettery.get_remainder_range()  # The current battery remaining capacity can continue driving 250 km

Related readings


<< prev | Python... Continue strolling Python Files... | next >>

If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: