【问题标题】:Why does it say that my instance has no attribute x?为什么它说我的实例没有属性 x?
【发布时间】: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() 中工作?

【问题讨论】:

  • 您为什么希望实例具有该属性?
  • 您应该发布一些重现问题的最少代码。

标签: python class pygame


【解决方案1】:

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

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

每个班级。

【讨论】:

  • 那么应该在这条线上提出:if pygame.mouse.get_pos()[1] &gt; myarcher.y:
  • 如果 __init__ 方法被添加到 both 类中,就像我建议的那样,并适当地调用。
  • 请注意,问题的后半部分是在我发布答案之后添加的
猜你喜欢
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多