Question

I have the following classes defined in 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

And I call them as such:

myarcher = Archer()
if pygame.mouse.get_pos()[1] > myarcher.y:
    myarcher = ArcherDown()
else:
    myarcher = Archer()

myarcher.draw(myarcher.x, myarcher.y, 'right')

However, this raises the error:

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'

This only gives an error for ArcherDown(), not Archer(). Any idea why?

Also, when I add __init__ as follows:

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 is always 100, which I don't want.

I can tell that x is not defined in ArcherDown(), but then why is it working in Archer()?

Was it helpful?

Solution

That's because you never set an initial value for x and y in either ArcherDown or Archer. You can solve this problem by adding a method such as

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

to each class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top