面向对象的编程错误

时间:2014-04-05 05:02:29

标签: python

class Ammo(Thing):

    # constructor here
    def __init__(self,name,weapon,quantity):
        self.name = name
        self.weapon = weapon
        self.quantity = quantity

    # definition of weapon_type here
    def weapon_type(self):
        return self.weapon

这是我的代码,当我尝试将weapon_type检索为string时 这是我的输入

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())   ## bow 

我没有得到bow而是获得<__main__.Weapon object at 0x0211DCB0>

1 个答案:

答案 0 :(得分:5)

arrows.weapon_type()目前会返回武器而不是字符串。 print 为您转换它,但我猜它打印的内容是这样的:

<__main__.Weapon object at 0x7ffea6de6208>

要让它打印更有用的东西,你可以控制它如何转换为字符串。 Print在其参数上调用内置函数str,调用方法__str__ - 换句话说,如果你像这样定义你的Weapon类:

class Weapon:
    # other methods
    def __str__(self):
        return self.type + " weapon"

然后str(a_weapon),以及print(a_weapon)扩展名会做更明智的事情。