Three characteristics of object-oriented languages: encapsulation inheritance polymorphism (2)-inheritance

1. What is inheritance?

In the program:

  • Extract the commonalities from two or more related classes, store the commonalities in a common class, and associate the common class with the common class through a specified method to form an inheritance system
  • Common class: called parent class/super class/base class; common class: called subclass
  • The relationship between the parent class and the child class: the child class comes 继承from the parent class; the parent class 派生produces the child class

Inherited pseudo code

#父类
class 父类类名:
	def __init__(self,形参列表):
		子类中的共同特征
	子类中的共同行为
	
#子类
class 子类类名(父类类名):
	def __init__(self, 共性字段列表, 个性字段的列表):
		#调用父类的位共性字段初始化的方式
		#为个性字段初始化赋值
	个性方法

Case:

Similar to the induction method of high school mathematics, general terms are summarized.
Each subcategory has its own unique characteristics.

Insert picture description here

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

    def eat(self):
        print(self.name, '吃饭')


class Student(Person):
    # 初始化学生对象时,不仅需要对个性赋值,还需要给共性赋值
    def __init__(self, name, age, sex, sid):
        # 需要调用父类中的为共性赋值的初始化方法
        """
        super --- 表示的是父类 Person
        self --- 表示的是当前类的对象
        super(): 创建一个父类对象
        创建对象的格式: 类名()
        """
        super().__init__(name, age, sex)

        # 为个性赋值
        self.sid = sid

    # 个性行为
    def study(self):
        # 需要使用父类中的字段 因为是继承关系 就像使用自己的一样 直接使用就行
        print(self.name, "在学习")


class worker(Person):
    def __init__(self, name, age, sex, wid):
        super().__init__(name, age, sex)
        self.wid = wid

    def work(self):
        print(self.name, "在工作")


def main():
    # 创建对象
    stu = Student("诡途", 18, "男", '0010')
    stu.eat()  # 父类方法
    stu.study()  # 子类方法

    # 创建对象
    wk = worker("天猫精灵", 20, "女", "1234")
    wk.eat()
    wk.work()


if __name__ == '__main__':
    main()

Insert picture description here

class Animal:
    def __init__(self, name, age, sex):
        self.__name = name
        self.__age = age
        self.__sex = sex

    @property
    def name(self):
        return self.__name

    # 这里的name是下面的set的name
    @name.setter
    def name(self, name):
        self.__name = name

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        if age < 0:
            self.__age = 0
        else:
            self.__age = age

    @property
    def sex(self):
        return self.__sex

    @sex.setter
    def sex(self, sex):
        if sex != "雌" and sex != "雄":
            self.__sex = "雌"
        else:
            self.__sex = sex


"""
父类中的共性特征都私有化了:
凡是私有化的内容的作用范围:仅限于当前类中,即使子类也无权访问
子类如果想访问,——使用父类提供的访问方式进行访问

如同子类还想通过普通的访问格式进行访问
需要把父类中的方法属性化才可以
"""


class Dog(Animal):
    def __init__(self, name, age, sex, breed):
        super().__init__(name, age, sex)
        self.bred = breed

    def eat_bone(self):
        print(self.name, "啃骨头")

    def look_home(self):
        print(self.name, "看家")


class Cat(Animal):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)

    def eat_fish(self):
        print(self.name, "吃鱼")

    def catch_mouse(self):
        print(self.name, "抓老鼠")


def main():
    cat = Cat("ketty", age=2, sex="雌")
    cat.eat_fish()
    print(cat.name, cat.sex)


if __name__ == '__main__':
    main()

2. Concepts in inheritance

  • Single inheritance: a class has and only one parent class

  • Multiple inheritance/multiple inheritance: A class can indirectly inherit multiple parent classes

  • Multiple inheritance: A class can have multiple parent classes [Python supports multiple inheritance], class subclasses (parent class 1, parent class 2, …)

Multi-level inheritance relationship: subclass-parent class-grandpa class-grandpa class,
indirect inheritance can also directly use commonality

#通过动物体系演示概念
#狗 : dog、蝙蝠: bat、鹦鹉: parrot、鸵鸟: ostrich、

Animal 顶级类

​	哺乳类Mammal和鸟类Bird 次级顶类

	​	哺乳类: 狗 蝙蝠
	
	​	鸟类: 鹦鹉 鸵鸟

	能跑的runnable 和 能飞的flyable
	
		runnable:狗 鹦鹉 鸵鸟
		
		flyable:蝙蝠 鹦鹉 

Insert picture description here

class Animal:
    pass
class Runnable:
    pass
class Flyable:
    pass
# 哺乳类
class Mammal(Animal):
    pass
class Bird(Animal):
    pass
class Dog(Mammal, Runnable):
    pass
class Parrot(Bird, Flyable):
    pass

Python supports multiple inheritance, C++ also supports multiple inheritance, Java only supports single inheritance

#查看类的父类
类名.__bases__
# 查看Student的父类
print(Student.__bases__)
>>> (<class '__main__.Person'>,)

# 查看Person 的父类
print(Person.__bases__)
>>>(<class 'object'>,)

object root class:

  • Object category: root category-ancestors in the genealogy
  • All classes are direct or indirect subclasses of object
  • There is no mark who inherited from, the default is to inherit from object

3. Method rewriting

The subclass rewrites the method in the parent class.
When the subclass rewrites the method in the parent class, the subclass calls the method after the subclass rewrites.

When will it be rewritten?

  • The implementation of this function in the subclass can be overridden if the parent class cannot satisfy the subclass

Rewrite type

  • Custom method override
  • System method rewrite.

Insert picture description here

Insert picture description here

class Bird:
    def __init__(self, color):
        self.color = color

    '''
    鸟类         攻击行为
    小红鸟 --- 死撞
    小黑鸟 --- 爆炸
    小黄鸟 --- 加速
    小蓝鸟 --- 分裂
    '''

    def attach(self):
        print("父类中的攻击实现")


class RedBird(Bird):
    def __init__(self, color):
        super().__init__(color)

    # 攻击行为: 子类中的方法声明与父类中的方法声明一致  实现功能的内容部分可以不一样
    def attach(self):
        # 当子类重写了父类中的方法,子类再调用该方法时 调用的是子类重写之后的
        # 子类重写之后 还想实现父类中方法的功能 可以在子类重写的方法中 通过super去调用
        super().attach()
        print("死撞")

def main():
    rb = RedBird("红色")
    rb.attach()

if __name__ == "__main__":
    main()

>>>父类中的攻击实现  #实现父类方法
>>>死撞  #实现子类中重写方法

【Previous】Three characteristics of object-oriented languages: encapsulation and inheritance polymorphism (1)-encapsulation

Guess you like

Origin blog.csdn.net/qq_35866846/article/details/108238271