【发布时间】:2014-06-21 10:10:19
【问题描述】:
我在 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() 中工作?
【问题讨论】:
-
您为什么希望实例具有该属性?
-
您应该发布一些重现问题的最少代码。