[英]Object-oriented programming error
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
这是我的代码,当我尝试以string
的weapon_type
获取weapon_type
,这是我的输入
bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type()) ## bow
我不bow
而是得到<__main__.Weapon object at 0x0211DCB0>
arrows.weapon_type()
当前将返回Weapon而不是字符串。 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)
会做得更明智。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.