鱼C论坛

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

[已解决]类对象

[复制链接]
发表于 2021-10-25 15:12:45 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 luck78 于 2021-10-25 15:14 编辑
  1. class Animal():
  2.     def __init__(self,name):
  3.         self.name = name
  4.     def greet(self):
  5.         print('Hello, I am an %s.' % self.name)
  6. class Dog(Animal):
  7.     def greet(self):
  8.         print('Wangwang... I am an %s.'% self.name)
  9.     def run(self):
  10.         print('I am running')

  11. class Cat(Animal):
  12.     def greet(self):
  13.         print(f"MiaoMiao... I am {self.name}")

  14. def hello[color=Red](animal):[/color]
  15.     animal.greet()
复制代码


请问为什么16行小写animal 也可以运作
可是父类class  Animal是大写
最佳答案
2021-10-25 16:34:12
  1. class Animal():
  2.     def __init__(self,name):
  3.         self.name = name
  4.     def greet(self):
  5.         print('Hello, I am an %s.' % self.name)
  6. class Dog(Animal):
  7.     def greet(self):
  8.         print('Wangwang... I am an %s.'% self.name)
  9.     def run(self):
  10.         print('I am running')

  11. class Cat(Animal):
  12.     def greet(self):
  13.         print(f"MiaoMiao... I am {self.name}")

  14. def hello(animal): # 这里的 animal 只是参数
  15.     animal.greet()

  16. hello(Animal("小白")) # 参数就是 Animal 类
复制代码
打印:
  1. Hello, I am an 小白.
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-10-25 15:19:45 | 显示全部楼层
第16行是函数定义,不是类定义,括号中的animal是函数的形参(普通变量),不是类的名称。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-10-25 16:34:12 | 显示全部楼层    本楼为最佳答案   
  1. class Animal():
  2.     def __init__(self,name):
  3.         self.name = name
  4.     def greet(self):
  5.         print('Hello, I am an %s.' % self.name)
  6. class Dog(Animal):
  7.     def greet(self):
  8.         print('Wangwang... I am an %s.'% self.name)
  9.     def run(self):
  10.         print('I am running')

  11. class Cat(Animal):
  12.     def greet(self):
  13.         print(f"MiaoMiao... I am {self.name}")

  14. def hello(animal): # 这里的 animal 只是参数
  15.     animal.greet()

  16. hello(Animal("小白")) # 参数就是 Animal 类
复制代码
打印:
  1. Hello, I am an 小白.
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-11 03:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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