Discuss / Python / 问题

问题

Topic source

醉后诀

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

def run_twice(animal): animal.run() animal.run()

#这个函数是写在animal类内还是类外的,这很重要

醉后诀

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

是写在类外的,可以理解为传入的参数只要是个对象并且有run()的方法就可以了

左手天才T

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

为什么是def run_twice(animal) 而不是 def run_twice(Animal) 我搞不懂

class Animal(object):
    def run(self):
        print('Animal is running...')

    def run_twice (animal):
        animal.run()
        animal.run()

class Dog(Animal):
    def run(self):
        print('Dog is running...')

class Cat(Animal):
    def run(self):
        print('Cat is running...')
a = Animal()
d = Dog()
c = Cat()

a.run_twice()
d.run_twice()
c.run_twice()
Animal is running...
Animal is running...
Dog is running...
Dog is running...
Cat is running...
Cat is running...

类内类外都一样,Dog,Cat都继承了Animal的

不,写在类内确实是继承 如果写在类外面,只是单纯表示传入的数据类型(cat dog)刚好拥有run这个方法,所以才正常运行了

#一句话总结应该是 写在里面表示 正常的派生继承 子类都拥有run twice 这个方法

#单是写在外面则表示 并非是继承,只是因为动态语言的鸭子特性,所以才能正常运行这个函数。任何定义的拥有run方法的类以及他的子类 都可以来使用run twice这个函数。 而JAVA这种静态型语言就不行,他只能通过写在里面通过继承功能才能运行,写在外面的话是运行不了的

刚刚学习,也没有学习过JAVA 看了评论以及自己一些百度之后理解的动态语言的鸭子特性,有不对的地方望指正 另外我查到说静态语言 java c++这种 在定义函数的时候,需要指明函数变量的类型 而动态语言python这种 在定义函数的时候,并没有这要求 他可以是任意类型的

惟莉V雅爱

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

明白了明白了,他这里就把self参数的名字定义为了animal,其实传入的还是self参数,即其类本身

惟莉V雅爱

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

三楼的类内函数定义感觉有问题,类内方法的定义不是要求第一个参数必须是self?,否则的话岂不是定义在了类外而不是animal的类函数,但是缩进方面又不是类外,而且运行起来也是他们的类函数,,还请大神解读一下,,,

宇少Jason

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

文中的方法应该是在类外,一是因为没有self,二是这里要表达鸭子类型,放在类内就没有意义了。 请大家一起讨论:

def run_twice(animal): animal.run() animal.run()

我的理解是把这个函数看做与类无关的一个函数,传入实例后执行的命令时“实例.run()”,只要这个类中有run()方法,就能正常运行。

小喵biubiu

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

写在类内,Dog和Cat基于继承,Timer基于鸭子特性 写在类外,三者均基于鸭子特性

你们的重点搞错了吧,继承还是鸭子特性它们的重点在run方法啊 a = Animal() d = Dog() c = Cat() run_twice写在里边,调用是: a.run_twice() d.run_twice() c.run_twice() run_twice写在外边,调用是: run_twice(a) run_twice(b) run_twice(c)

不管run_twice在类里边还是外边,继承或者鸭子特性都是通过run方法体现的,不过,run_twice写在里边,与run方法一样,体现了继承和鸭子特性。


Reply