[英]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.