[2021 Spring] CS61A 学习笔记 lecture17 Inheritance + Composition

lecture 17: 继承和组合
主要内容:以“动物保护区”为例,讲解

  • 类的继承,"is-a","是一个"的关系
  • 类的对象组合,"has-a","有一个"的关系

Inheritance 继承

一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,新类称为子类。
子类可以定义自己的属性和方法,重写(覆盖)父类的同名属性和方法。super()表示调用父类。
可以参考菜鸟教程
父类:

class Animal:
    species_name = "Animal"
    scientific_name = "Animalia"
    play_multiplier = 2
    interact_increment = 1

    def __init__ (self, name, age=0):
        self.name = name
        self.age = age
        self.calories_eaten  = 0
        self.happiness = 0

    def play(self, num_hours):
        self.happiness += (num_hours * self.play_multiplier)
        print("WHEEE PLAY TIME!" )

    def eat(self, food):
        self.calories_eaten += food.calories
        print(f"Om nom nom yummy {food.name}")
        if self.calories_eaten > self.calories_needed:
            self.happiness -= 1
            print( "Ugh so full" )

    def interact_with (self, animal2 ):
        self.happiness += self.interact_increment
        print(f"Yay happy fun time with {animal2.name}")

子类

重写类变量和方法

Subclasses can override existing class variables and assign new class variables.
If a subclass overrides a method, Python will use that definition instead of the superclass definition.

class Panda(Animal):
    species_name = "Giant Panda"
    scientific_name = "Ailuropoda melanoleuca"
    calories_needed = 6000
    def interact_with (self, other):
        print(f"I'm a Panda, I'm solitary, go away {other.name}!")

使用父类方法

To refer to a superclass method, we can use super():

class Lion(Animal):
    species_name = "Lion"
    scientific_name = "Panthera"
    calories_needed = 3000

    def eat (self, food):
        if food.type == "meat":
            super().eat(food)
            # Animal.eat(food)

bones = Food( "Bones", "meat")
mufasa = Lion("Mufasa" , 10)
mufasa.eat(bones)

关于super()

重写__init__

继承的层数


多类继承



identity检查

组合

一个对象可以包含对其他类的对象的引用。
An object can contain references to objects of other classes.
What examples of composition are in an animal conservatory?

  • An animal has a mate.
  • An animal has a mother.
  • An animal has children.
  • A conservatory has animals.

引用其他实例

引用实例列表

通用接口

继承和组合的比较

posted @ 2021-07-04 00:02  ikventure  阅读(266)  评论(0编辑  收藏  举报