Introduction
Why: object oriented is more in line with human's abstraction and understanding of the objective world
-
Everything is the object
A puppy, a chair, a credit card, a chocolate... -
All objects have their own internal attributes
Dog breed, chair texture, credit card limit, chocolate taste... -
All actions are actions of the object
Dog squatting, chair moving, credit card swiping, chocolate melting...
How: class is the carrier of object
Every cat of different age, color and quality is an object
They have one thing in common: they are all cats
We can abstract the common features of a class of objects and create a general class
# Create class class Cat(): """Simulated cat""" def __init__(self, name): """Initialize properties""" self.name = name def jump(self): """Simulated cat jumping""" print(self.name + " is jumping")
# Create instance with class my_cat = Cat("Loser") your_cat = Cat("Lucky")
# Call attribute print(my_cat.name) print(your_cat.name)
Loser Lucky
# Calling method my_cat.jump() your_cat.jump()
Loser is jumping Lucky is jumping
7.1 definition of category
Three elements: class name, attribute and method
7.1.1 class naming
-
Have practical significance
-
Hump Nomenclature - capitalized words
Dog, CreditCard, ElectricCar
# class name: """It's better to leave two lines blank before class""" class Car(): """A brief introduction to this class""" pass """It's better to leave two lines blank after class"""
7.1.2 properties of class
#Def init (self, parameter to pass) initializes the properties of the classclass Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of the car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0
7.1.3 methods
#Functions defined relative to the classclass Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of the car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0 def get_main_information(self): # self can't save """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{}".format(self.brand, self.model, self.year)) def get_mileage(self): """Get total mileage""" return "Total mileage:{}kilometre".format(self.mileage)
My_Car = Car("Audi","sb",2019)
print(My_Car.get_mileage())Total mileage: 0 km
7.2 create an instance
7.2.1 instance creation
Assign an instance to an object, and pass in the corresponding parameters during instantiation
v = class name (required initialization parameters)
my_new_car = Car("Audi", "A6", 2018)
7.2.2 access properties
Instance name. Property name
print(my_new_car.brand) print(my_new_car.model) print(my_new_car.year)
Audi A6 2018
7.2.3 call method
class Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0 def get_main_information(self): # self can't save """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{}".format(self.brand, self.model, self.year)) def get_mileage(self): """Get total mileage""" return "Total mileage:{}kilometre".format(self.mileage)
Instance name. Method name (required parameters)
my_new_car = Car("Audi", "A6", 2018) my_new_car.get_main_information()Brand: Audi model: A6 factory year: 2018
mileage = my_new_car.get_mileage() print(mileage)Total mileage: 0 km
7.2.4 modifying attributes
1. Direct modification
my_old_car = Car("BYD", "Song Dynasty", 2016)
Access first, then modify
print(my_old_car.mileage) my_old_car.mileage = 12000 print(my_old_car.mileage)0 12000
print(my_old_car.get_mileage())Total mileage: 12000km
2. Modify properties by method
class Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0 def get_main_information(self): # self can't save """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{}".format(self.brand, self.model, self.year)) def get_mileage(self): """Get total mileage""" return "Total mileage:{}kilometre".format(self.mileage) def set_mileage(self, distance): """Set total mileage""" self.mileage = distance
my_old_car = Car("BYD", "Song Dynasty", 2016) print(my_old_car.get_mileage()) my_old_car.set_mileage(8000) print(my_old_car.get_mileage())Total mileage: 0 km Brand: BYD model: Song ex factory year: 2016 Total mileage: 8000 km
3. Continue to expand
- Do not set negative mileage
class Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of the car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0 def get_main_information(self): # self can't save """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{}".format(self.brand, self.model, self.year)) def get_mileage(self): """Get total mileage""" print("Total mileage:{}kilometre".format(self.mileage)) def set_mileage(self, distance): """Set total mileage""" if distance >= 0: self.mileage = distance else: print("Mileage cannot be negative!") def increment_mileage(self, distance): """Total mileage accumulation""" if distance >= 0: self.mileage += distance else: print("New mileage cannot be negative!")
my_old_car = Car("BYD", "Song Dynasty", 2016) my_old_car.get_mileage() my_old_car.set_mileage(-8000) my_old_car.get_mileage()Total mileage: 0 km Mileage cannot be negative! Total mileage: 0 km
- Add up mileage each time
my_old_car.get_mileage() my_old_car.set_mileage(8000) my_old_car.get_mileage() my_old_car.increment_mileage(500) my_old_car.get_mileage()Total mileage: 0 km Total mileage: 8000 km Total mileage: 8500km
Summary
my_new_car = Car("Audi", "A6", 2018) my_cars = [my_new_car, my_old_car]
- It can contain a huge amount of information and create an infinite number of instances
- Highly anthropomorphic, in line with human's abstract and understanding of the objective world
7.3 class inheritance
Introduction
Take a look at the branch chain of human beings in the biological world
Biology -- zoology -- chordate -- mammalia -- primates -- human family -- human genus -- Homo sapiens
The process of increasing public features
[question]
Suppose the binary system: human =
Construct a class for everyone
Scenario 1:
They are independent and construct their own ethnic groups
Option two:
1. To extract the public characteristics of each race and establish the human genus;
2. Each race inherits the public characteristics of the upper class (human genus), and then adds its own special characteristics to construct its own race class.
Usually, we choose option 2, because it avoids too much duplication of labor
The so-called inheritance is the process of low-level abstraction inheriting high-level abstraction
7.3.1 simple inheritance
Parent class
class Car(): """Simulated vehicle""" def __init__(self, brand, model, year): """Initialize car properties""" # Equivalent to a variable within a class self.brand = brand # Brand of automobile self.model = model # Model of car self.year = year # Vehicle year of manufacture self.mileage = 0 # The total mileage of the new car is initialized to 0 def get_main_information(self): # self can't save """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{}".format(self.brand, self.model, self.year)) def get_mileage(self): """Get total mileage""" print("Total mileage:{}kilometre".format(self.mileage)) def set_mileage(self, distance): """Set total mileage""" if distance >= 0: self.mileage = distance else: print("Mileage cannot be negative!") def increment_mileage(self, distance): """Total mileage accumulation""" if distance >= 0: self.mileage += distance else: print("New mileage cannot be negative!")
Subclass
Class subclass name (parent class name):
- Build a new class of electric vehicles
class ElectricCar(Car): """Simulated electric vehicle""" def __init__(self, brand, model, year): """Initialize EV properties""" super().__init__(brand, model,year) # Declare properties that inherit from the parent class
A = ElectricCar("au","23",90)
- Automatically inherit all methods of the parent class
my_electric_car = ElectricCar("NextWeek", "FF91", 2046) my_electric_car.get_main_information()
'Brand: NextWeek Model: FF91 Year of manufacture: 2046'
7.3.2 add attributes and methods to subclasses
class ElectricCar(Car): """Simulated electric vehicle""" def __init__(self, brand, model, year, bettery_size): """Initialize EV properties""" super().__init__(brand, model, year) # Declare properties that inherit from the parent class self.bettery_size = bettery_size # Battery capacity self.electric_quantity = bettery_size # Remaining battery capacity self.electric2distance_ratio = 5 # Power distance conversion factor 5km / kW.h self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage def get_electric_quantit(self): """View current battery level""" print("Current battery capacity:{} kW.h".format(self.electric_quantity)) def set_electric_quantity(self, electric_quantity): """Set the remaining battery capacity and recalculate the battery capacity to support the mileage""" 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 power is not set in a reasonable range!") def get_remainder_range(self): """View remaining mileage""" print("The current power can still drive {} kilometre".format(self.remainder_range))
my_electric_car = ElectricCar("NextWeek", "FF91", 2046, 70) my_electric_car.get_electric_quantit() # Get current battery power my_electric_car.get_remainder_range() # Get the current remaining mileageCurrent remaining battery capacity: 70 kW.h The current power can continue to drive 350 kilometers
my_electric_car.set_electric_quantity(50) # Reset battery level my_electric_car.get_electric_quantit() # Get current battery power my_electric_car.get_remainder_range() # Get the current remaining mileageCurrent remaining battery capacity: 50 kW.h The current power can continue to drive 250 kilometers
7.3.3 method of overriding parent class polymorphism
class ElectricCar(Car): """Simulated electric vehicle""" def __init__(self, brand, model, year, bettery_size): """Initialize EV properties""" super().__init__(brand, model, year) # Declare properties that inherit from the parent class self.bettery_size = bettery_size # Battery capacity self.electric_quantity = bettery_size # Remaining battery capacity self.electric2distance_ratio = 5 # Power distance conversion factor 5km / kW.h self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage def get_main_information(self): # Override parent method """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{} Mileage:{} kilometre" .format(self.brand, self.model, self.year, self.bettery_size*self.electric2distance_ratio)) def get_electric_quantit(self): """Check the current battery power and recalculate the power to support the mileage""" print("Current battery capacity:{} kW.h".format(self.electric_quantity)) def set_electric_quantity(self, electric_quantity): """Set the remaining battery capacity""" 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 power is not set in a reasonable range!") def get_remainder_range(self): """View remaining mileage""" print("The current power can still drive {} kilometre".format(self.remainder_range))
my_electric_car = ElectricCar("NextWeek", "FF91", 2046, 70) my_electric_car.get_main_information()Brand: NextWeek model: FF91 factory year: 2046 mileage: 350 km
7.3.4 examples used in classes
Abstract the battery into an object
Clearer logic
class Bettery(): """Battery of analog electric vehicle""" def __init__(self, bettery_size = 70): self.bettery_size = bettery_size # Battery capacity self.electric_quantity = bettery_size # Remaining battery capacity self.electric2distance_ratio = 5 # Power distance conversion factor 5km / kW.h self.remainder_range = self.electric_quantity*self.electric2distance_ratio # Remaining mileage def get_electric_quantit(self): """View current battery level""" print("Current battery capacity:{} kW.h".format(self.electric_quantity)) def set_electric_quantity(self, electric_quantity): """Set the remaining battery capacity, and recalculate the battery capacity to support the mileage""" 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 power is not set in a reasonable range!") def get_remainder_range(self): """View remaining mileage""" print("The current power can still drive {} kilometre".format(self.remainder_range))
class ElectricCar(Car): """Simulated electric vehicle""" def __init__(self, brand, model, year, bettery_size): """Initialize EV properties""" super().__init__(brand, model, year) # Declare properties that inherit from the parent class self.bettery = Bettery(bettery_size) # Battery def get_main_information(self): # Override parent method """Get the main information of the car""" print("Brand:{} Model:{} Year of manufacture:{} Mileage:{} kilometre" .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() # Access to main vehicle informationBrand: NextWeek model: FF91 factory year: 2046 mileage: 350 km
my_electric_car.bettery.get_electric_quantit() # Get current battery powerCurrent remaining battery capacity: 70 kW.h
my_electric_car.bettery.set_electric_quantity(50) # Reset battery level
my_electric_car.bettery.get_electric_quantit() # Get current battery powerCurrent remaining battery capacity: 50 kW.h
my_electric_car.bettery.get_remainder_range() # Get the current remaining mileageThe current power can continue to drive 250 kilometers Faye Published 14 original articles, praised 15, visited 517 Private letter follow