Three introductory Python relationship like (dependent / combination / inheritance)

Three introductory Python relationship like (dependent / combination / inheritance)

In object-oriented, there are three relationships between classes: dependencies, combination or succession.

1, the dependency: the class name of a class or object passed as arguments to another function relationship is used dependencies

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} 打开冰箱")

    def close_door(self,p):
        print(f"{p.name} 关闭冰箱")


r = People("大魔")   # People类实例化一个对象r
aux = Refrigerator("奥克斯")   # Refrigerator类实例化一个对象aux
r.open(aux)    # 将aux对象当做参数传递给r对象的open方法使用
r.close(aux)   # 将aux对象当做参数传递给r对象的close方法使用

2, the relationship between the combination of: a class object is encapsulated into another attribute of the object class, called combination

class Boy:

    def __init__(self,name,g):
        self.name = name    # self = b
        self.g = g         # g就是girl类实例化的一个对象内存地址

    def eat(self):
        print(f"{self.name}和{self.g.age}岁,且{self.g.weight}公斤的{self.g.name}py朋友.一起吃了个烛光晚餐!")

    def make_keep(self):
        self.g.live(f"{self.g.weight}公斤的{self.g.name}给{self.name}踩背")


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"直播内容:{argv}")


g = Girl("乔毕得",54,"女",220)
b = Boy("太博",g)    # 将对象g当做属性封装到b对象的属性中
b.make_keep()

3, inheritance

(1) What is object-oriented inheritance

Inheritance (English: inheritance) is a concept of object-oriented software technology among. If a category A "inherited from" Another category B, put the A is called "sub-category B", and B is called the "father of category A" can also be called "B of A is a superclass." Inheritance can have various subcategories such properties and methods of the parent class, without the need to write the same code again. While Reiko category inherit the parent class, you can re-define certain attributes, and override some methods, properties and methods of the original parent category that is covered, so to get the parent category different functions. In addition, for the subcategory additional new properties and methods it is also common practice.
General static object-oriented programming language, inherited a static, meaning it has been decided to compile in the behavior of sub-categories, can not expand in the implementation period.

(2) procedure A (B)

<1> A - subclass, derived class

<2> B - parent class, the base class, the superclass

When we write more classes will 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("吃")

class Dog:

    def __init__(self, name, age, sex):
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):
        print("吃")

class Cat:

    def __init__(self, name, age, sex):
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):
        print("吃")

class Pig:

    def __init__(self, name, age, sex):
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):
        print("吃")

The code is repeated, then we can simplify the relevant code such as:

class Animal: # 父类
    """
    动物类
    """
    live = "活的"

    def __init__(self, name, age, sex):
        print("is __init__")
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):  # self 是函数的位置参数
        print("吃")

class Human(Animal): # 子类
    pass

class Dog(Animal):  # 子类
    pass

class Cat(Animal):  # 子类
    pass

class Pig(Animal):  # 子类
    pass

(3) inherited advantages:

<1> to reduce duplication of code

<2> clear structure and norms

<3> increased coupling (coupling not appropriate, in fine)

(4) inherited Category:

<1> single inheritance

<2> multiple inheritance

Python2: python2.2 之前都是经典类,python2.2之后出现了新式类,继承object就是新式类
Python3: 只有新式类,不管你继不继承object都是新式类

(5) single inheritance:

<1> through the class name of the subclass properties and methods of the parent class

class Animal: # 父类

    live = "活的"

    def __init__(self, name, age, sex):
        print("is __init__")
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):  # self 是函数的位置参数
        print("吃")

class Human(Animal): # 子类
    pass

class Dog(Animal):  # 子类
    pass
    
Human.eat(12)
Human.__init__(Human,"大魔",18,"男")

print(Human.live)
print(Human.__dict__)

<2> The subclasses of the object properties and methods of the parent class

class Animal: # 父类

    live = "活的"

    def __init__(self, name, age, sex):
        print("is __init__")
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):  # self 是函数的位置参数
        print("吃")

class Human(Animal): # 子类
    pass

class Dog(Animal):  # 子类
    pass
    
p = Human("大魔",18,"男")
d = Dog("remmom",1,'母')
print(d.__dict__)
print(p.__dict__)

p = Human("大魔",18,"男")
print(p.live)

(6) search order:

<1> irreversible (proximity principle)

<2> by subclassing, properties or methods of the parent class using the class name (search order): the current class, the current class of the parent, the parent class the parent class of the current class ---->

<3> subclass object by using the parent class property or method (search order): go first object, an instance of this object class, the current class of the parent class --->

(7) use subclasses and superclasses methods or properties:

<1> Method a: not rely on (no) Inherited

class Animal: # 父类

    live = "活的"

    def __init__(self, name, age, sex):
        # self = p的内存地址
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):  # self 是函数的位置参数
        print("吃")

class Human: # 子类

    def __init__(self, name, age, sex, hobby):
        # print(Animal.live)
        # self = p的内存地址
        Animal.__init__(self,name,age,sex)  # 直接使用Animal类调用Animal类中的方法
        self.hobby = hobby

class Dog:

    def __init__(self, name, age, sex, attitude):
        # self = p的内存地址
        self.name = name
        self.sex = sex
        self.age = age
        self.attitude = attitude      # 与Human类进行比较


p = Human("大魔",18,"男","健身")
print(p.__dict__)

<2> Method II: dependence (required) Inherited

class Animal: # 父类

    live = "活的"

    def __init__(self, name, age, sex):
        # self = p的内存地址
        self.name = name
        self.sex = sex
        self.age = age

    def eat(self):  # self 是函数的位置参数
        print("吃")
        
   class Dog(Animal):

    def __init__(self, name, age, sex, attitude):
        # self = p的内存地址
        # super(Dog,self).__init__(name,age,sex)   # 完整写法
        super().__init__(name,age,sex)   # 正常写法  # 通过super方法使用父类中的方法
        self.attitude = attitude

d = Dog("大魔",18,"男","忠诚")
print(d.__dict__)

Exercise Exercise:

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 inherited multiple parent classes

Multiple inheritance, there are so ⼀ a problem. When two ⽗ class appeared in the same name Remedies time. Will involve how to find such a problem ⽗ ⼀ class Remedies That MRO (method resolution order) problem. ⼀ in python this is a very complex issue because the Use of different versions of python manipulation are different algorithms to complete the MRO.

(1) Classic: from left to right when executed multiple inheritance

class A:
    name = "小宝"

class B(A):
    name = "太博"

class C(A):
    name = "marry"

class D(B, C):
    name = "魔22"

class E:
    name = "魔11"

class F(E):
    name = "魔"

class G(F, D):
    name = "bb"
    
class H:
    name = "aaa"

class Foo(H, G):
    pass

f = Foo()
print(f.name)

#  结果为aaa

to sum up:

Classic :( depth-first) priority to the left, a road go head will return to the starting point can not find the right query

(2) new categories: c3 using algorithm (also a breadth-first speaking - imprecise)

# 下述例子在python2.7中运行
class O(object):
    name = "小宝"

class D(O):
    name = "天魔"

class E(O):
    name = "太博"

class F(O):
    name = "marry"

class B(D,E):
    pass

class C(E,F):
    name = "金刚"

class A(B,C):
    pass

a = A()
print a.name

#  结果为     天魔

Core mro (3) c3 algorithm

<1> mro () - python may be provided a method for performing sequential view when multiple inheritance
<2> MRO is an ordered list L, the class is created when it is calculated. General formula is:
mro(Child(Base1,Base2)) = [ Child ] + merge( mro(Base1), mro(Base2), [ Base1, Base2] )
(其中Child继承自Base1, Base2)
If a base class to inherit: class B (A) is a time sequence B mro
mro( B ) = mro( B(A) )
= [B] + merge( mro(A) + [A] )
= [B] + merge( [A] + [A] )
= [B,A]
If the successor to the plurality of base classes: class B (A1, A2, A3 ...) mro time sequence B
mro(B) = mro( B(A1, A2, A3 …) )
= [B] + merge( mro(A1), mro(A2), mro(A3) ..., [A1, A2, A3] )
= ...
The results as a list, a list of at least one element i.e. the class itself, as in the examples [A1, A2, A3]. merge operation is a core C3 algorithm.
<3> headers and footers
Header: The first element of the list
Footer: head elements other than a list of tables set (which may be empty)

List of examples: [A, B, C] is the header A, B and C footer

<4> + action between the list

+ Operation:

[A] + [B] = [A, B] (the default calculations shown) ---------------------

merge operation example:

如计算merge( [E,O], [C,E,F,O], [C] )
有三个列表 :  ①        ②      ③

1 merge不为空,取出第一个列表列表①的表头E,进行判断                              
   各个列表的表尾分别是[O], [E,F,O],E在这些表尾的集合中,因而跳过当前当前列表
2 取出列表②的表头C,进行判断
   C不在各个列表的集合中,因而将C拿出到merge外,并从所有表头删除
   merge( [E,O], [C,E,F,O], [C]) = [C] + merge( [E,O], [E,F,O] )
3 进行下一次新的merge操作 ......
---------------------
<5> Classic can not be used mro, the new class can use mro

Guess you like

Origin www.cnblogs.com/caiyongliang/p/11576280.html