class Tank(object):
def _init_(self,name):
self.name = name
self.alive = True
self.ammo = 5
self.armor = 60
def _str_(self):
if self.alive:
return "%s (%i armor and %i shells left)"%(self.name,self.armor,self.ammo)
else:
return "%s is DEAD !" % self.name
def fire_at(self,enemy):
if self.ammo >= 1:
self.ammo-=1
print(self.name," fires on ",enemy.name)
enemy.hit()
else:
print(self.name," has no shells!")
def hit(Self):
self.armor-=20
print(self.name," is hit !")
if self.armor<=0:
self.explode()
def explode(self):
self.alive = False
print(self.name," explodes !!!!")
from tank import Tank
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Crane") }
alive_tanks = len(tanks)
while alive_tanks > 1:
print()
for tank_name in sorted(tanks):
print(tank_name,tanks[tank_name])
first = raw_input("Who fires ?").lower()
second = raw_input("Who at ?").lower()
try:
first_tank = tanks[first]
second_tank = tanks[second]
except KeyError:
print("No such Tank ")
continue
if not first_tank.alive or not second_tank.alive:
print("One of those is dead!")
continue
print()
print("*"*30)
first_tank.fire_at(second_tank)
if not second_tank.alive:
alive_tanks -= 1
print("*"*30)
for tank in tanks.value():
if tank.alive:
print(tank.name," is the winner !")
break
运行时出现错误:
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Crane") }
TypeError: object() takes no parameters
我需要解决什么?
答案 0 :(得分:1)
类init方法是ddunder方法,如果没有调用默认的init方法,则需要在该方法前后声明两个下划线。
__init__(self, name)
代替
_init_(self, name)
str方法也一样,它必须是:
__str__