Three things like getting started with Python (dependencies/combinations/inheritance relationships)
In object-oriented, there are three relationships between classes: dependency, combination and inheritance.
1. Dependency: A relationship in which the class name or object of a class is passed as an argument to another function is used is a dependency.
class People: def __init__(self,name): self.name = name def open(self,bx): bx.open_door(self) def close(self,bx): bx.close_door(self) class Refrigerator: def __init__(self,name): self.name = name def open_door(self,p): print(f"{p.name} Open the refrigerator") def close_door(self,p): print(f"{p.name} Close refrigerator") r = People("Magic") # People class instantiates an object r aux = Refrigerator("Ox") # Refrigerator class instantiates an object aux r.open(aux) # The open method that passes the aux object as a parameter to the r object uses r.close(aux) # The close method that passes the aux object as an argument to the r object uses
2. Combinatorial Relationships: Encapsulating objects of one class into attributes of objects of another class is called combination
class Boy: def __init__(self,name,g): self.name = name # self = b self.g = g # g is an object memory address instantiated by the girl class def eat(self): print(f"{self.name}and{self.g.age}year,And{self.g.weight}Kilogram{self.g.name}py Friend.We had a candlelit dinner together!") def make_keep(self): self.g.live(f"{self.g.weight}Kilogram{self.g.name}to{self.name}Back Stepping") class Girl: def __init__(self,name,age,sex,weight,*args): self.name = name self.age = age self.sex = sex self.weight = weight self.args = args def live(self,argv): print(f"Live content:{argv}") g = Girl("Jobid",54,"female",220) b = Boy("Tabo",g) # Encapsulate object g as an attribute in the properties of object b b.make_keep()
3. Inheritance Relations
(1) What is object-oriented inheritance
Inheritance (English: inheritance) is a concept in object-oriented software technology.If one category A "inherits" from another category B, it is called a "sub-category of B", and B is also called a "parent category of A" or a "superclass of B".Inheritance allows subcategories to have various properties and methods of the parent class without having to write the same code again.While having subcategories inherit the parent category, you can redefine some properties and override some methods, that is, override the original properties and methods of the parent category to achieve functionality different from that of the parent category.Adding new attributes and methods to subcategories is also a common practice.
In general, static object-oriented programming languages, inheritance is static, meaning that the behavior of subcategories is determined at compile time and cannot be expanded at execution time.
(2) A(B) in the program
<1> A -- Subclass, Derived Class
<2> B -- parent class, base class, superclass
When we write multiple classes, we find many problems such as:
class Human: def __init__(self,name,age,sex): self.name = name self.sex = sex self.age = age def eat(self): print("eat") class Dog: def __init__(self, name, age, sex): self.name = name self.sex = sex self.age = age def eat(self): print("eat") class Cat: def __init__(self, name, age, sex): self.name = name self.sex = sex self.age = age def eat(self): print("eat") class Pig: def __init__(self, name, age, sex): self.name = name self.sex = sex self.age = age def eat(self): print("eat")
The above code is duplicated, so we can simplify the related code such as:
class Animal: # Parent Class """ //Animals """ live = "Living" def __init__(self, name, age, sex): print("is __init__") self.name = name self.sex = sex self.age = age def eat(self): # self is the position parameter of the function print("eat") class Human(Animal): # Subclass pass class Dog(Animal): # Subclass pass class Cat(Animal): # Subclass pass class Pig(Animal): # Subclass pass
(3) Advantages of inheritance:
<1>Reduce duplicate code
<2>Clear structure, specification
<3>Increase coupling (less coupling, in essence)
(4) Classification of inheritance:
<1>Single Inheritance
<2>Multiple Inheritance
Python 2: Previously, Python 2.2 was a classic class. After Python 2.2, new classes appeared. Inheriting object s is a new class Python3: Only new-style classes, new-style classes regardless of whether you succeed in inheriting object s
(5) Single inheritance:
<1>Use the properties and methods of the parent through the class name of the subclass
class Animal: # Parent Class live = "Living" def __init__(self, name, age, sex): print("is __init__") self.name = name self.sex = sex self.age = age def eat(self): # self is the position parameter of the function print("eat") class Human(Animal): # Subclass pass class Dog(Animal): # Subclass pass Human.eat(12) Human.__init__(Human,"Magic",18,"male") print(Human.live) print(Human.__dict__)
<2>Use parent class properties and methods through subclass objects
class Animal: # Parent Class live = "Living" def __init__(self, name, age, sex): print("is __init__") self.name = name self.sex = sex self.age = age def eat(self): # self is the position parameter of the function print("eat") class Human(Animal): # Subclass pass class Dog(Animal): # Subclass pass p = Human("Magic",18,"male") d = Dog("remmom",1,'mother') print(d.__dict__) print(p.__dict__) p = Human("Magic",18,"male") print(p.live)
(6) Search order:
<1>Irreversible (proximity principle)
<2>Through subclasses, class names use attributes or methods of the parent class (lookup order): the current class, the parent of the current class, the parent of the parent of the current class---->
<3>Use properties or methods of the parent class (lookup order) through subclass objects: first find the object, instantiate the class of this object, parent of the current class--->
(7) Use both child and parent methods or attributes:
<1>Method 1: Independent (unnecessary) inheritance
class Animal: # Parent Class live = "Living" def __init__(self, name, age, sex): # self = p's memory address self.name = name self.sex = sex self.age = age def eat(self): # self is the position parameter of the function print("eat") class Human: # Subclass def __init__(self, name, age, sex, hobby): # print(Animal.live) # self = p's memory address Animal.__init__(self,name,age,sex) # Calling methods in Animal classes directly using the Animal class self.hobby = hobby class Dog: def __init__(self, name, age, sex, attitude): # self = p's memory address self.name = name self.sex = sex self.age = age self.attitude = attitude # Compare with the Human class p = Human("Magic",18,"male","Bodybuilding") print(p.__dict__)
<2>Method 2: Dependent (Needed) Inheritance
class Animal: # Parent Class live = "Living" def __init__(self, name, age, sex): # self = p's memory address self.name = name self.sex = sex self.age = age def eat(self): # self is the position parameter of the function print("eat") class Dog(Animal): def __init__(self, name, age, sex, attitude): # self = p's memory address # super(Dog,self).__init__(name,age,sex) # Complete Writing super().__init__(name,age,sex) # Normal Writing # Using methods in the parent class through the super method self.attitude = attitude d = Dog("Magic",18,"male","loyal") print(d.__dict__)
Exercises:
class Base: def __init__(self, num): self.num = num def func1(self): print(self.num) self.func2() def func2(self): print("Base.func2") class Foo(Base): def func2(self): print("Foo.func2") obj = Foo(123) obj.func1()
class Base: def __init__(self, num): self.num = num def func1(self): print(self.num) self.func2() def func2(self): print(111, self.num) class Foo(Base): def func2(self): print(222, self.num) lst = [Base(1), Base(2), Foo(3)] for obj in lst: obj.func1()
(8) Multiple Inheritance
Multiple inheritance is inheriting multiple parent classes
In multiple inheritance, there is such a problem. When the duplicate name method appears in two_classes, it involves how to find such a problem. That is, the MRO problem. In python, this is a very complex problem. Because different Python versions make_different calculationsMethod to complete the MRO.
(1) Classic Class: Execute left-to-right when multiple inheritances occur
class A: name = "Xiaobao" class B(A): name = "Tabo" class C(A): name = "marry" class D(B, C): name = "Magic 22" class E: name = "Magic 11" class F(E): name = "magic" class G(F, D): name = "bb" class H: name = "aaa" class Foo(H, G): pass f = Foo() print(f.name) # The result is aaa
Summary:
Classic Class: (Depth first) Left first, one way to the end, can't find it will return to the starting point and query right
(2) New class: using c3 algorithm (also referred to as breadth first--imprecise)
# The following example runs in Python 2.7 class O(object): name = "Xiaobao" class D(O): name = "Devil" class E(O): name = "Tabo" class F(O): name = "marry" class B(D,E): pass class C(E,F): name = "Peter Jackson's King Kong" class A(B,C): pass a = A() print a.name # The result is a demon
(3) core mro of c3 algorithm
<1> mro() -- A method provided by Python to see the execution order of multiple inheritance
<2> MRO is an ordered list L that is calculated when the class is created.The general formula is:
mro(Child(Base1,Base2)) = [ Child ] + merge( mro(Base1), mro(Base2), [ Base1, Base2] ) (among Child Inherited from Base1, Base2)
If inherited to a base class: class B(A), then B's mro sequence is
mro( B ) = mro( B(A) ) = [B] + merge( mro(A) + [A] ) = [B] + merge( [A] + [A] ) = [B,A]
If inherited to multiple base classes: class B(A1, A2, A3...) At this time B's mro sequence
mro(B) = mro( B(A1, A2, A3 ...) ) = [B] + merge( mro(A1), mro(A2), mro(A3) ..., [A1, A2, A3] ) = ...
The result is a list of at least one element in the list, the class itself, as in the example [A1,A2,A3] above.merge operation is the core of C3 algorithm.
<3>Header and End
Header: The first element of the list
End of Table: A set of elements (which can be empty) outside the header in the list
Example List: [A, B, C] Header is A, End is B and C
+action between <4>lists
+Operation:
[A] + [B] = [A, B] (omitted by default in the following calculations) ---------------------------------
Example merge operation:
For example, calculate merge ([E, O], [C, E, F, O], [C]) There are three lists: 1, 2, 3 1 merge is not empty, take the header E of the first list 1 for judgment The tails of each list are [O], [E,F,O], and E is in the set of these tails, skipping the current list 2 Remove the header C of List 2 for judgment C is not in the collection of lists, so take C out of merge and delete it from all headers merge( [E,O], [C,E,F,O], [C]) = [C] + merge( [E,O], [E,F,O] ) 3Perform the next merge operation... ---------------------