encapsulation
It can be simply understood as hiding all the implementation details that can be hidden, only providing a simple programming interface to the outside world. The method we define in the class is to encapsulate the operation of data and data. After we create the object, we can execute the code in the method only by sending a message to the object (calling the method). That is to say, we only need to know the name of the method and the parameters (external view of the method). Figure) without knowing the implementation details inside the method (the internal view of the method).
Exercise: Define a class to implement a number of numbers
import time class Clock: def __init__(self): # Get the current system time t = time.localtime() self._hour = t.tm_hour self._minute = t.tm_min self._second = t.tm_sec def run(self): self._second += 1 if self._second == 60: self._second = 0 self._minute += 1 if self._minute == 60: self._minute = 0 self._hour += 1 if self._hour == 24: self._hour = 0 def show(self): return "%02d:%02d:%02d" % (self._hour, self._minute, self._second) def main(): clock = Clock() while True: # Return the cursor to the current header print("\r%s" % clock.show(), end="") time.sleep(1) clock.run() if __name__ == '__main__': main()
inherit
In real life, inheritance generally refers to children inheriting the property of their parents, as shown below.
No, the results are as follows.
Inheritance in a program describes the relationship between things, such as cats and dogs belong to animals, which can be described as cat and dog inheritance automata. Similarly, Persian cats and Bali cats inherit from cats, while sandpigs and spotted dogs inherit from dogs, as follows:
Subclasses can inherit the public attributes and methods of the parent class, and private attributes and methods of the parent class can not be inherited.
single inheritance
Generally, inheriting only one parent class is called single inheritance. In static languages such as java, only one parent class can be inherited, so there is no single inheritance and multiple inheritance.
Sample code:
# Define a parent class as follows: class Cat(object): def __init__(self, name, color="white"): self.name = name self.color = color def run(self): print("%s--Running"%self.name) # Define a subclass that inherits Cat classes as follows: class Bosi(Cat): # If the subclass does not implement the _init_ method, the _init_ method of the parent class is automatically invoked. def setNewName(self, newName): self.name = newName def eat(self): print("%s--Eat at"%self.name) bs = Bosi("Indian cat") print('bs The name is:%s'%bs.name) print('bs The color of the product is ___________.:%s'%bs.color) bs.eat() bs.setNewName('Persia') bs.run() """ //Output results: bs The name is:Indian cat bs The color of the product is ___________.:white //Indian Cat--Eating //Persia--Running """
Multiple Inheritance
As can be seen from the graph, the so-called multi-inheritance means that subclasses have multiple parent classes and have their characteristics.
The format of multi-inheritance is as follows:
# Define a parent class class A: def printA(self): print('----A----') # Define a parent class class B: def printB(self): print('----B----') # Define a subclass that inherits from A and B class C(A,B): def printC(self): print('----C----') obj_C = C() obj_C.printA() obj_C.printB() """ //Output results: ----A---- ----B---- """
If in the example of multiple inheritance above, if there is a method with the same name in the parent class A and B, which one will be called when the method is called through the child class?
class A: def print(self): print('----A----') class B: def print(self): print('----B----') # Define a subclass that inherits from A and B class C(A,B): pass obj_C = C() obj_C.print() """ //Output results: ----A---- """
In fact, the order of invocation depends on which class C inherits first, and the class inherited first will be invoked.
You can also use _mor_ to see the sequence of object search methods in class C, followed by the above code.
print(C.__mro__) """ //Output results: (<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>) """
Method of overwriting parent class
Rewriting is a method with the same name as the parent class in a subclass. The method in the subclass overrides the method with the same name in the parent class.
class Cat: def sayHello(self): print("halou-----1") class Bosi(Cat): def sayHello(self): print("halou-----2") class Bali(Cat): def sayHello(self): print("halou-----3") bosi = Bosi() bali= Bali() bosi.sayHello() bali.sayHello() """ //Output results: halou-----2 halou-----3 """
Through method rewriting, we can make the same behavior of the parent class have different implementation versions in the subclass. When we call the method rewritten by the subclass, different subclass objects will show different behavior, which is poly morphism.
Calling methods of parent classes
class Cat: def __init__(self,name): self.name = name class Bosi(Cat): def __init__(self,name): # Calling the _init_ method 1 of the parent class (python 2) #Cat.__init__(self,name) # Calling the _init_ method 2 of the parent class #super(Bosi,self).__init__(name) # Calling the _init_ method 3 of the parent class super().__init__(name) self.color = 'yellow' def getName(self): return self.name bosi = Bosi('xiaohua') print(bosi.name) print(bosi.color) """ //Output results: xiaohua yellow """
Summary:
- As mentioned above, if you need a parent constructor in a subclass, you need to explicitly call the parent constructor, or do not override the parent constructor, the subclass does not override init, and the init defined by the parent class is automatically invoked when the subclass is instantiated.
- If the subclass overrides _init_, instantiating the subclass does not invoke the init defined by the parent class.
- If you override _init_, you can inherit the construction method of the parent class by using the following methods:
- Super (subclass, self). _init_ (parameter 1, parameter 2,...)
- Parent class name. _init_ (self, parameter 1, parameter 2,...)
polymorphic
The concept of polymorphism is applied to strongly typed languages such as Java and C #, while Python advocates "duck type".