鱼C论坛

 找回密码
 立即注册
查看: 1079|回复: 2

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

[复制链接]
发表于 2021-12-23 20:30:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class Animal(object):
  2.     def run(self):
  3.         print('Animal is run')
  4.     def run__twice(animal):
  5.         animal.run()
  6.         animal.run()
  7. class Tortoise(Animal):
  8.     def run(self):
  9.         print('Tortoise is running srlowly')
  10. tortoise=Tortoise()       //为Tortoise实例化一个对象
  11. tortoise.run__twice()    //tortoise调用run__twice()函数,为社么会打印两遍“Tortoise is running srlowly”出来呢?当torsoise调用run__twice函数的时候,传入run__twice的参数是什么呢?
复制代码
最佳答案
2021-12-23 21:31:48
def run__twice(animal): 类函数定义正常第一个参数是self,然后这个animal被环境自动纠正了。
写还是规范一点比较好
  1. class Animal(object):  # 定义动物类
  2.     def run(self):
  3.         print('Animal is run')

  4.     def run__twice(self):
  5.         self.run()
  6.         self.run()


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


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

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-12-23 21:31:48 | 显示全部楼层    本楼为最佳答案   
def run__twice(animal): 类函数定义正常第一个参数是self,然后这个animal被环境自动纠正了。
写还是规范一点比较好
  1. class Animal(object):  # 定义动物类
  2.     def run(self):
  3.         print('Animal is run')

  4.     def run__twice(self):
  5.         self.run()
  6.         self.run()


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


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

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2021-12-24 09:35:52 | 显示全部楼层
suchocolate 发表于 2021-12-23 21:31
def run__twice(animal): 类函数定义正常第一个参数是self,然后这个animal被环境自动纠正了。
写还是规范 ...

明白了,感谢大佬帮忙!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 18:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表