鹿酸梅 发表于 2021-12-23 20:30:57

请大佬帮忙解释下这段代码调用时的逻辑,对运行结果有点不明白。谢谢!

class Animal(object):
    def run(self):
      print('Animal is run')
    def run__twice(animal):
      animal.run()
      animal.run()
class Tortoise(Animal):
    def run(self):
      print('Tortoise is running srlowly')
tortoise=Tortoise()       //为Tortoise实例化一个对象
tortoise.run__twice()    //tortoise调用run__twice()函数,为社么会打印两遍“Tortoise is running srlowly”出来呢?当torsoise调用run__twice函数的时候,传入run__twice的参数是什么呢?

suchocolate 发表于 2021-12-23 21:31:48

def run__twice(animal): 类函数定义正常第一个参数是self,然后这个animal被环境自动纠正了。
写还是规范一点比较好class Animal(object):# 定义动物类
    def run(self):
      print('Animal is run')

    def run__twice(self):
      self.run()
      self.run()


class Tortoise(Animal):# 定义龟类,继承自动物类
    def run(self):# 对父类的跑函数重写
      print('Tortoise is running srlowly')


tortoise = Tortoise()# 实例化龟,继承一个函数run__twice,重写一个函数run。
tortoise.run__twice()# 执行继承的函数,这个函数调用了两次重写的函数。

鹿酸梅 发表于 2021-12-24 09:35:52

suchocolate 发表于 2021-12-23 21:31
def run__twice(animal): 类函数定义正常第一个参数是self,然后这个animal被环境自动纠正了。
写还是规范 ...

明白了,感谢大佬帮忙!
页: [1]
查看完整版本: 请大佬帮忙解释下这段代码调用时的逻辑,对运行结果有点不明白。谢谢!