Python3 | 鸭子类型

鸭子类型的含义与其在 python 中的表现形式

Posted by Haauleon on May 14, 2021

鸭子类型



在 python 中的表现形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Duck:
    def quack(self): 
        print("呱呱呱!")
    def feathers(self): 
        print("这个鸭子拥有灰白灰白的羽毛。")
 
class Person:
    def quack(self):
        print("哈哈哈哈哈哈哈哈哈哈你在说啥")
    def feathers(self): 
        print("这个人穿着一件鸭绒大衣。")
 
def in_the_forest(duck):
    duck.quack()
    duck.feathers()
 
def game():
    donald = Duck()
    john = Person()
    in_the_forest(donald)
    in_the_forest(john)
 
game()