我在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()
中工作呢?你知道吗
这是因为在
ArcherDown
或Archer
中从未为x
和y
设置初始值。您可以通过添加以下方法来解决此问题:给每个班级。你知道吗
相关问题 更多 >
编程相关推荐