Python advanced training - Num1, inheritance, polymorphism

Posted by marcusb on Mon, 03 Jan 2022 19:50:33 +0100

  • Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
  • Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object.
  • Polymorphism: functions with different functions can use the same function name, so that functions with different contents (functions) can be called with one function name.

Create class:

class classname:

#Class body. Class members, methods, and data attributes

self represents the instance of the class and the parameter name

__ init__ Method receive parameters

In the interior of a class, you can define a method for the class by using the "def" keyword. Unlike general function definitions, the class method must contain the parameter self and be the first parameter

Use a point number To access the properties of the object

  • getattr(obj, name[, default]): access the properties of the object.
  • hasattr(obj,name): check whether an attribute exists.
  • setattr(obj,name,value): set an attribute. If the property does not exist, a new property is created.
  • delattr(obj, name): deletes an attribute.

Inheritance syntax:

Class derived class name (base class name)
    ...

If you need the constructor of the parent class in a subclass, you need to explicitly call the constructor of the parent class or do not override the constructor of the parent class.

If rewritten__ init__ To inherit the constructor of the parent class, you can use the super keyword:

Super (subclass, self)__ init__ (parameter 1, parameter 2,...)

Case 1: the subclass needs to automatically call the method of the parent class: the subclass does not override__ init__ () method. After instantiating a subclass, it will automatically call the parent class__ init__ () method.

Case 2: the subclass does not need to automatically call the method of the parent class: subclass override__ init__ () method. After instantiating a subclass, the parent class will not be called automatically__ init__ () method.

Case 3: subclass override__ init__ () method needs to call the method of the parent class: use super keyword:

Super (subclass, self)__ init__ (parameter 1, parameter 2,...)
class Son(Father):
  def __init__(self, name):   
    super(Son, self).__init__(name)

Multiple inheritance:

class SubClassName (ParentClass1[, ParentClass2, ...]):
    ...


Python does not allow instantiated classes to access private data, but you can use {object_ className__ Attrname (object name. Class name private property name) access property

Operator overloading:

1__init__ ( self [,args...] )
Constructor
Simple call method: obj = className(args)
2__del__( self )
Destruct method to delete an object
Simple call method: del obj
3__repr__( self )
Converted to a form for the interpreter to read
Simple call method: repr(obj)
4__str__( self )
Used to convert a value into a human readable form
Simple call method: str(obj)
5__cmp__ ( self, x )
Object comparison
Simple call method: cmp(obj, x)

example:

class vehicle:#Define base class
    def __init__(self,type,weight,drive):#__ init__  Methods receive various parameters, vehicle type and weight
        self.type=type  #Assignment type
        self.weight=weight#Assign weight
        self.drive=drive
    def display(self): #Define the output class. Output parameter values
        print ("Model:",self.type,"Weight:",self.weight,"t","Driving conditions:",self.drive)


class bus(vehicle):#The subclass inherits the constructor of the parent class
    def display(self):#Define the output class. Output the values of parameters and rewrite the output function
        print ("name:",self.type,"  Weight:",self.weight,"t"," Driving conditions:",self.drive)

car1=vehicle("automobile",1.5,"Driverless")#Create the first object of the vehicle class
car2=vehicle("Passenger car",2.5,"Driverless")#Create the second object of the vehicle class
car1.display()#Output properties
car2.display()#Output properties
bus1=bus("Dongfeng Road No. 28 bus", 2.5,"Driverless")#Create the first object of the bus class
bus1.display()#Output properties

 

class vehicle:#Define base class
    def __init__(self,weight,drive):#__ init__  Methods receive various parameters, vehicle type and weight
        self.weight=weight#Assign weight
        self.drive=drive#Assign drive
    def display(self): #Define the output class. Output parameter values
        print ("Weight:",self.weight,"t","Driving conditions:",self.drive)

class bus1(vehicle):#Polymorphic functions with different functions can use the same function name to define bus1 inheritance base class
    def __init__(self,weight,drive,type):
        super().__init__(weight,drive) #super inherits the constructor of the parent class, as shown below
        self.type=type#Define new properties
    def display(self):
        print ("name:",self.type,"  Weight:",self.weight,"t"," Driving conditions:",self.drive)

class bus2(vehicle):#Define bus2 inherited base class
    def __init__(self,weight,drive,type):
        super().__init__(weight,drive)
        self.type=type
    def display(self):
        print ("First name 2:",self.type,"Weight:",self.weight,"t"," Driving conditions:",self.drive)

class bus3(vehicle):#Define bus3 inheritance base class
    def __init__(self,weight,drive,type):
        super().__init__(weight,drive)
        self.type=type
    def display(self):
        print ("First name 3:",self.type,"Weight:",self.weight,"t"," Driving conditions:",self.drive)

bus4=bus1(2.5,"Driverless","28 No. bus")#Create the first object of the bus1 class
bus4.display()
bus5=bus2(3.5,"Human driving","906 No. bus")#Create the first object of the bus2 class
bus5.display()
bus6=bus3(4.5,"Human driving","B32 No. bus")#Create the first object of the bus3 class
bus6.display()

Learning 2: Python object-oriented promotion and sending and receiving mail_ Beep beep beep_ bilibili

If the method name in the parent class is the same, the method in the parent class in front of the bracket will be called by default

The contents of another folder are called in Python:

1. Under the same file directory

Use the following two statements in the b.py file to call the func() function in the a.py file

import a # reference module
a.func( )

Or

import a# reference module
 from a # import func # refers to a function in a module
 func() # there is no need to prefix the module name when calling the function here

2. Under different file directories

If it is not in the same directory and python cannot find it, you must set the search path and add the folder where the module is located to the system search path

import sys 
sys.path.append('path of a.py ')
import a 
a.func()

Multiple inheritance:

class SubclassName(BaseClass1, BaseClass2, BaseClass3, ...):
    pass

Polymorphism: multiple forms of a thing

Object properties take precedence over class properties

Class attribute: class name call

Dynamically add object attributes to objects

Never duplicate the names of object attributes and class attributes, because object attributes will mask class attributes, but class attributes can be used after deleting object attributes

 

Topics: Python C++ data structure Container