[英]Calling a method from another class in Python
我当前的文件中有一个叫做Rabbits
的类(称为rabbits.py
)。 在Rabbits
,我有一种称为carrots()
的方法。
在另一个文件中,我有一个名为Whales
的类(在名为whales.py
的文件中)。 在“ Whales
我有一种称为swimming()
的方法。
如果我要在carrots()
中打印一个字符串,其中包含swimming()
返回的内容; 我该怎么办? 是print(str(self.whales.swimming())
吗?
我不断收到以下错误:
AttributeError: 'str' object has no attribute 'name'
您的战斗机拥有一种武器,因此可以调用武器的方法:
# weapon.py
class Weapon:
def __init__(self, name, dmg):
self.name = name
self.dmg = dmg
def attack(self, target):
target.health -= self.dmg
# fighter.py
class Fighter:
def __init__(self, name, weapon=None):
self.name = name
self.weapon = weapon
def attack(self, target):
if self.weapon is None:
# punch him
target.health -= 2
else:
self.weapon.attack(target)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.