为什么说我的实例没有属性x?

时间:2014-05-05 07:14:57

标签: python class pygame

我在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()中有效?

1 个答案:

答案 0 :(得分:1)

这是因为您从未在xy中为ArcherDownArcher设置初始值。您可以通过添加

等方法来解决此问题
def __init__(self, x, y):
  self.x = x
  self.y = y

每个班级。