我已經定義了下面的代碼,但似乎有關於方法load
和damage
的問題。python面向對象編程方法
(由ShadowRanger編輯的基礎上建議):
class RangedWeapon(Weapon):
def __init__(self, name, min_dmg, max_dmg):
super().__init__(name, min_dmg, max_dmg)
self.shots=0
def shots_left(self):
return self.shots
def load(self, ammo):
if ammo.weapon_type()==self.name:
self.shots+=ammo.get_quantity()
ammo.remove_all()
def damage(self):
if self.shots==0:
return 0
else:
self.shots-=1
return super().damage()
_
bow = RangedWeapon('bow', 10, 40)
crossbow = RangedWeapon('crossbow', 15, 45)
arrows = Ammo('arrow', bow, 5)
bolts = Ammo('bolt', crossbow, 10)
bow.load(arrows)
print(bow.shots_left()) # should return 5
print(arrows.get_quantity()) #should return 0
但print(bow.shots_left())
我得到0和print(arrows.get_quantity())
我有5來代替。它們被顛倒過來。我認爲我的問題是我沒有加載彈藥數量?我不是很確定。任何幫助,將不勝感激。謝謝!
class Ammo(Thing):
def __init__(self, name, weapon, quantity):
self.name=name
self.weapon=weapon
self.quantity=quantity
def get_quantity(self):
return self.quantity
def weapon_type(self):
return self.weapon.name
def remove_all(self):
self.quantity=0
「Ammo」類看起來像什麼? –
你的加載函數應該使用'ammo'變量而不是類'Ammo' – Weijian
我不知道這個代碼是如何在你的解釋器中執行的;我已經可以看到至少兩個運行時錯誤,這會導致該程序的執行失敗 –