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

2024-06-13 15:04:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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()中工作呢?你知道吗


Tags: selfmovedefremoveclassprintdrawshot
1条回答
网友
1楼 · 发布于 2024-06-13 15:04:24

这是因为在ArcherDownArcher中从未为xy设置初始值。您可以通过添加以下方法来解决此问题:

def __init__(self, x, y):
  self.x = x
  self.y = y

给每个班级。你知道吗

相关问题 更多 >