Asmor
Asmor

Reputation: 5181

Python property being ignored, acting like an attribute

I've got this RoomPlaceholder class with a distance property; when you set the distance property, it should automatically calculate what the x and y of the class should be, based on a random angle and the distance.

class RoomPlaceholder:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(8))
        self.angle = Util.getRandomAngle() # = random.random() * math.pi * 2
        self.distance = 0

    @property
    def distance(self):
        print "gamma"
        return self._distance
    @distance.setter
    def distance(self, value):
        print "delta"
        self._distance = value
        coords = Util.getXYByDist(value, self.angle) # translates angle and distance into integer (x, y)
        print coords
        self._x = coords[0]
        self._y = coords[1]

    @property
    def x(self):
        return self._x
    @property
    def y(self):
        return self._y

    def __repr__(self):
        return "%s: [%sx%s] @ (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)

if __name__ == "__main__":
    room = RoomPlaceholder(5,5)
    print "%s\n" % room.distance
    room.distance = 10
    print "%s\n" % room.distance
    print room
    pass

However, it's not working. Based on the output from the console, it looks like it's treating distance as an attribute rather than a property; note that I've got print statements in both the getter ("gamma") and setter ("delta") methods, but we never see either in the output when I get or set the distance:

Traceback (most recent call last):0

  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 142, in <module>

10

    print room
  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 132, in __repr__
    return "%s: [%sx%s] @ (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)
  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 97, in x
    return self._x
AttributeError: RoomPlaceholder instance has no attribute '_x'
[Finished in 0.0s]

I'm using Python 2.7, and this is being run via Sublime Text 3 in Windows 7.

Upvotes: 1

Views: 314

Answers (1)

jwodder
jwodder

Reputation: 57630

property only works for new-style classes. You need to make RoomPlaceholder a subclass of object by declaring it thusly:

class RoomPlaceholder(object):
    # etc.

Upvotes: 5

Related Questions