新手,又出错了
class Gun:def __init__(self,model):
self.model = model
self.bulletcount = 0
def add(self,count):
self.bulletcount += count
def shoot(self):
if self.bulletcount<= 0 :
print('%s没有子弹')%self.model
return
self.bulletcount -= 1
print('突突突。。%s[%d]'%(self.model,self.bulletcount))
class Soldier:
def __init__(self,name):
self.name = name
self.gun = None
def fire(self):
if self.gun == None:
print('%s没有枪'%self.name)
return
print("冲啊!!!%s"%self.name)
self.gun.add(6)
self.gun.shoot()
ak47= Gun("AK47")
xusanduo = Soldier
xusanduo.gun = ak47
xusanduo.fire()
print(xusanduo.gun)
in <module>
xusanduo.fire()
TypeError: fire() missing 1 required positional argument: 'self'
差哪里了
改成这样:
xusanduo = Soldier() 类实例化必须得加上括号,所以代码应该这么改:
class Gun:
def __init__(self,model):
self.model = model
self.bulletcount = 0
def add(self,count):
self.bulletcount += count
def shoot(self):
if self.bulletcount<= 0 :
print('%s没有子弹')%self.model
return
self.bulletcount -= 1
print('突突突。。%s[%d]'%(self.model,self.bulletcount))
class Soldier:
def __init__(self,name):
self.name = name
self.gun = None
def fire(self):
if self.gun == None:
print('%s没有枪'%self.name)
return
print("冲啊!!!%s"%self.name)
self.gun.add(6)
self.gun.shoot()
ak47= Gun("AK47")
xusanduo = Soldier()
xusanduo.gun = ak47
xusanduo.fire()
print(xusanduo.gun) 测试发帖 xusanduo = Soldier
这句话少打了一个括号
xusanduo = Soldier() 成这样:
xusanduo = Soldier() class Gun:
def __init__(self,model):
self.model = model
self.bulletcount = 0
def add(self,count):
self.bulletcount += count
def shoot(self):
if self.bulletcount<= 0 :
print('%s没有子弹')%self.model
return
self.bulletcount -= 1
print('突突突。。%s[%d]'%(self.model,self.bulletcount))
class Soldier:
def __init__(self,name):
self.name = name
self.gun = None
def fire(self):
if self.gun == None:
print('%s没有枪'%self.name)
return
print("冲啊!!!%s"%self.name)
self.gun.add(6)
self.gun.shoot()
ak47= Gun("AK47")
xusanduo = Soldier()
xusanduo.gun = ak47
xusanduo.fire()
print(xusanduo.gun)
页:
[1]