代码实现:

class Human: def init(self, name): self.name = name

def talk_business(self):
    print(f"{self.name} is talking business.")

class Superman(Human): def init(self, name): super().init(name)

def talk_business(self):
    print(f"{self.name} is talking business in a super way.")

def fly(self):
    print(f"{self.name} is flying.")

测试

human = Human("Tom") superman = Superman("Clark")

print(human.name) # 输出 "Tom" print(superman.name) # 输出 "Clark"

human.talk_business() # 输出 "Tom is talking business." superman.talk_business() # 输出 "Clark is talking business in a super way."

superman.fly() # 输出 "Clark is flying.

定义人类和超人分别在人类和超人类中定义名字属性和谈生意功能并且 在超人类中重写人类的谈生意功能最后在超人类中定义特有的飞翔功能分析1因为人类和超人类中都有相同属性姓名和方法谈生意因此想到了继承关系将事物共性抽取到父类中剩余类型作为子类存在于是人类作为父类超人类作为子类2超人类中需要重写谈生意功能超人还有特有方法飞翔

原文地址: https://www.cveoy.top/t/topic/f2mT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录