我在python中定义了以下类:
class ArcherDown:
def draw(self, x, y, direction):
self.x = x
self.y = y
def move(self, newx, newy, direction):
self.x+=newx
self.y+=newy
self.draw(self.x, self.y, direction)
def shoot(self, x, y):
print 'Shot!'
def remove(self, x, y):
pass
class Archer:
def draw(self, x, y, direction):
self.x = x
self.y = y
def move(self, newx, newy, direction):
self.x+=newx
self.y+=newy
self.draw(self.x, self.y, direction)
def shoot(self, x, y):
print 'Shot!'
def remove(self, x, y):
pass
我称之为:
myarcher = Archer()
if pygame.mouse.get_pos()[1] > myarcher.y:
myarcher = ArcherDown()
else:
myarcher = Archer()
myarcher.draw(myarcher.x, myarcher.y, 'right')
但是,这会引发错误:
Traceback (most recent call last):
File "game.py", line 7, in <module>
myarcher.draw(myarcher.x, myarcher.y, direction)
AttributeError: ArcherDown instance has no attribute 'x'
这只会给ArcherDown()
而不是Archer()
带来错误。知道为什么吗?
另外,当我按如下方式添加__init__
时:
class ArcherDown:
def __init__(self):
self.x = 100
self.y = 100
def draw(self, x, y, direction):
self.x = x
self.y = y
def move(self, newx, newy, direction):
self.x+=newx
self.y+=newy
self.draw(self.x, self.y, direction)
def shoot(self, x, y):
print 'Shot!'
def remove(self, x, y):
pass
class Archer:
def draw(self, x, y, direction):
self.x = x
self.y = y
def move(self, newx, newy, direction):
self.x+=newx
self.y+=newy
self.draw(self.x, self.y, direction)
def shoot(self, x, y):
print 'Shot!'
def remove(self, x, y):
pass
self.x
总是100
,我不想要。
我可以说x
中没有定义ArcherDown()
,但为什么它在Archer()
中有效?
答案 0 :(得分:1)
这是因为您从未在x
或y
中为ArcherDown
和Archer
设置初始值。您可以通过添加
def __init__(self, x, y):
self.x = x
self.y = y
每个班级。