在Python中从另一个类调用方法

在Python中从另一个类调用方法,python,class,Python,Class,我在当前文件中有一个名为rabbes的类(名为rabbs.py)。 在rabbts中,我有一个名为carrots()的方法 在另一个文件中,我有一个名为whates(在一个名为whates.py的文件中)的类。 在whates中,我有一个名为swiming()的方法 如果我试图在carrots()中打印一个字符串,其中包含swiming()返回的内容;我该怎么做?它会是print(str(self.whates.swiming()) 我不断得到以下错误: AttributeError: 'str

我在当前文件中有一个名为
rabbes
的类(名为
rabbs.py
)。 在
rabbts
中,我有一个名为
carrots()
的方法

在另一个文件中,我有一个名为
whates
(在一个名为
whates.py
的文件中)的类。 在
whates
中,我有一个名为
swiming()
的方法

如果我试图在
carrots()
中打印一个字符串,其中包含
swiming()返回的内容
;我该怎么做?它会是
print(str(self.whates.swiming())

我不断得到以下错误:

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)

您是否可以包含代码以查看您是如何创建实例的?为什么您认为在您的类上调用另一个类的方法是明智的做法?“游泳会返回什么?”-什么鲸鱼在游泳?为什么你的兔子有鲸鱼?我怀疑你可能错过了课程的目的。为了更简单的目的,我刚刚重命名了信息。一个课程是战斗机,另一个是武器。战斗机必须使用武器的攻击方法。为了将来的参考,这种重命名模糊了关系对象之间的IP。我不认为这会让问题变得更短。