Discuss / Python / 个人理解的鸭子类型,如果不对还望指出

个人理解的鸭子类型,如果不对还望指出

Topic source

人渣14396

#1 Created at ... [Delete] [Delete and Lock User]
class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    def run(self):
        print('Dog is running...')
class Cat(Animal):

    def run(self):
        print('Cat is running...')
class people():
    def run(self):
        print("people do not extends Animal")
def run_twice(animal):
    animal.run()
    animal.run()
run_twice(Cat())
run_twice(Animal())
run_twice(people())

上面这段代码关键点在于people这个类,这个类他并没有继承Animal这个父类,这也就出现了上面廖老师所讲的鸭子类型,因为run_twice这个函数中传入的参数是animal的,而people这个类却和animal没有任何关系,但是其中却有run这个方法,所以在调用run_twice这个函数时仍不会报错,也能正常输出people类中的内容

我按照这个程序运行,为什么出现错误。错误是:run()  missing a required a positional argument:'self'

石年80059

#3 Created at ... [Delete] [Delete and Lock User]

我觉得:def run_twice(animal):里面的animal理解不应该是class Animal,它实质就像是C语言中的形参,和class Animal没有半毛钱关系。就像class people一样,只要有run方法的都可以被def run_twice(animal)调用。

张D阿pANG

#4 Created at ... [Delete] [Delete and Lock User]

Agree with #3

筱君冬月

#5 Created at ... [Delete] [Delete and Lock User]

Agree with #3 +1

3#+1

run_twice(animal)里的animal太障眼了吧,把它换成x,以及下面两个animal.run()改成x.run()也一样

Ciq1n7

#7 Created at ... [Delete] [Delete and Lock User]

class people如果放twice后边会有影响吗

_啊马哥

#8 Created at ... [Delete] [Delete and Lock User]

赞同3#石年的说法,觉得def run_twice(animal):中的animal是个形参

人渣定义的people()里,少了object,所以会出错。

沧海奇迹1

#10 Created at ... [Delete] [Delete and Lock User]

事实上,把run_twice改成:

def run_twice(a):

    a.run()

    a.run()

也是可以的,所以这里的run_twice(Animal)中“Animal”和任何类都没有关系


  • 1
  • 2

Reply