Iron music learning python_day20_ object-oriented programming 2

object-oriented composition

In addition to inheritance, there is another important way of software reuse, namely: composition
Composition refers to the use of objects of another class as data attributes in one class, which is called class composition.

Example: Human-dog battle, humans bind weapons to attack dogs:

# 定义一个武器类
class Weapon:
    # 该武器的技能有劈砍
    def cleave(self, target):
        target.hp -= 50 # 劈砍技能对目标造成50点伤害

# 定义一个人类
class Person:
    def __init__(self, name, sex, hp, atk):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.atk = atk
        self.weapon = Weapon() # 给角色绑定一个武器

# 定义一个狗类
class Dog:
    def __init__(self, name, kind, hp, atk):
        self.name = name
        self.kind = kind
        self.hp = hp
        self.atk = atk

# 实例化一个人类角色
tiele = Person('tiele', '男', 30, 10, )
# 实例化一个狗类角色
xiaobai = Dog('小白', '金毛寻回犬', 60, 15)
# 人类装备上武器使用武器技能cleave进行攻击狗类
tiele.weapon.cleave(xiaobai) # 这种用法就叫做组合
print(xiaobai.hp)  # 显示10,表明目标的确hp-50了。

The relationship between the class and the combined class is established in a composite manner, which is a 'have' relationship. For example, characters have weapons, martial arts, etc.
Composition is better when the classes are significantly different and the smaller class is a required component of the larger class.

Another example where a teacher has classes to teach and birthday dates is as follows:

class BirthDate:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

class Course:
    def __init__(self, name, price, period):
        self.name = name
        self.price = price
        self.period = period

class Teacher:
    def __init__(self, name, sex, birth, course):
        self.name = name
        self.sex = sex
        self.birth = birth
        self.course = course

# 实例化一个老师的同时,传参的时候还可以传另一个实例化的对象
tiele = Teacher('铁乐', '男', BirthDate(1999, 4, 1), Course('python', '19800', '5 months'))
# 查看时可以直接用组合的方式查看
print(tiele.course.name, tiele.birth.year)  # python 1999
print(tiele.course.price, tiele.birth.month) # 19800 4

Three characteristics of object-oriented

They are inheritance, polymorphism, and encapsulation.

What is inheritance?
Inheritance is a way to create a new class.
In python, a new class can inherit one or more parent classes
.
Inheritance of classes in python is divided into: single inheritance and multiple inheritance.

class ParentClass1: #定义父类
    pass

class ParentClass2: #定义父类
    pass

#单继承,基类是ParentClass1,派生类是SubClass
class SubClass1(ParentClass1): 
    pass

#python支持多继承,用逗号分隔开多个继承的类
class SubClass2(ParentClass1,ParentClass2): 
    pass

# 查看继承
print(SubClass1.__bases__)
# __base__只查看从左到右继承的第一个子类,__bases__则是查看所有继承的父类
# (<class '__main__.ParentClass1'>,)
print(SubClass2.__bases__)
# (<class '__main__.ParentClass1'>, <class '__main__.ParentClass2'>)

如果没有指定基类,python的类会默认继承object类,object是所有python类的基类,
它提供了一些常见方法(如__str__)的实现。

print(ParentClass1.__base__)  # <class 'object'>
print(ParentClass2.__bases__) # (<class 'object'>,)

Inheritance and abstraction (first abstraction and then inheritance)

Abstraction is to extract similar or more similar parts.
The abstraction is divided into two levels:
1. Extract the similar parts of Obama and Messi into a class;
2. Extract the similar parts of the three classes of people, pigs, and dogs into a parent class.
The main function of abstraction is to divide categories (can isolate concerns and reduce complexity)

Inheritance: It is based on the result of abstraction. To realize it through a programming language, it must first go through the process of abstraction
before the abstract structure can be expressed through inheritance.
Abstraction is just an action or a technique in the process of analysis and design, and classes can be obtained through abstraction.

Inheritance and Reusability

In the process of developing a program, if we define a class A, and then want to create another class B,
but most of the content of class B is the same as that of class A,
we cannot write a class B from scratch, which The concept of class inheritance is used.
Create a new class B by inheritance, let B inherit A, and B will 'inherit' all attributes (data attributes and function attributes) of A
to achieve code reuse.

Create a new class with an existing class, which reuses a part of the existing software and most of the settings,
which greatly increases the programming workload. This is often referred to as software reuse. Not only can you reuse your own classes,
you can also Inheriting others, such as the standard library, to customize new data types,
which greatly shortens the software development cycle, which is of great significance to large-scale software development.

Derived

Of course, subclasses can also add their own new attributes or redefine these attributes on their own (will not affect the parent class)
. When it comes to properties, it is up to you.

In the subclass, the newly created function attribute with the same name, when editing the function in the function, it may be necessary to reuse the function function of the same name in the parent class, which
should be the way to call the ordinary function, namely: classname.func (), at this time it is no different from calling a normal function, so even the self parameter must be passed a value for it.
In python3, the super method can also be used directly by the subclass to execute the superclass method.

example:

class Animal:

    def __init__(self, name, hp, ad):
        self.name = name  # 对象属性 属性
        self.hp = hp  # 血量
        self.ad = ad  # 攻击力
    
    def eat(self, target):
        print('吃肉包子回血')
        target.hp += 10
        
class Person(Animal):  # 继承父类

    def __init__(self, name, hp, ad, sex):
        super().__init__(name, hp, ad) 
       # 使用super().__init__来继承父类属性的同时又可以同时有子类派生的属性
       # 在单继承中,super负责找到当前类所在的父类,在这个时候不需要再手动传self
        self.sex = sex
        self.money = 0  # 派生属性

class Dog(Animal):

    def __init__(self, name, hp, ad, kind):
        super().__init__(name, hp, ad)
        self.kind = kind

    def bite(self, p):     # 派生方法
        p.hp -= self.ad
        print('%s咬了%s一口,%s掉了%s点血' % (self.name, p.name, p.name, self.ad))
       super().eat(self)  # 使用super()---子类执行父类方法

super()

super is only used when the child and parent class has a method with the same name, and when you
want to use the object of the child class to call the method of the parent class, use super
super in the class: super(). Method name (arg1,..) Name
: parent Class name. Method name (self, arg1, ..)
in py2 super must pass parameters super (subclass name, self). Method name (arg...)
in single inheritance is simply looking for the parent class;
in multiple In inheritance, the next class is found according to the mro order of the graph where the child node is located.

Multiple Inheritance Diamond Inheritance

Classic classes: in python2, do not inherit object, follow the depth-first traversal algorithm when finding nodes;
new-style classes: all new-style classes in python3, inherit object in py2, follow the breadth-first traversal algorithm when finding nodes;
breadth-first: when a When a node can be accessed both in depth and breadth, it is preferentially searched from breadth (horizontal).
The class name.mro() method can view the breadth-first order;
the function of super(): view the previous node of the current class in breadth-first.

遇到多继承和super
    对象.方法
        找到这个对象对应的类
        将这个类的所有父类都找到画成一个图
        根据图写出广度优先的顺序
        再看代码,看代码的时候要根据广度优先顺序图来找对应的super

经典类 :在python2.*版本才存在,且必须不继承object
    遍历的时候遵循深度优先算法
    没有mro方法
    没有super()方法

新式类 :在python2.X的版本中,需要继承object才是新式类
    遍历的时候遵循广度优先算法
    在新式类中,有mro方法
    有super方法,但是在2.X版本的解释器中,必须传参数(子类名,子类对象)

The relationship between the derived class and the base class is established through inheritance. It is a 'yes' relationship, such as a white horse is a horse and a person is an animal.
When there are many common functions between classes, it is better to use inheritance to extract these common functions and make them into base classes.

end
2018-4-16

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324494060&siteId=291194637