0

I've just written this class:

class PhysicsObject: "An object that is physically simulated. Has velocity, position, and orientation." def __init__(self): self.velocity=Vector(0,0) self.position=Vector(0,0) self.heading=0 #This gives a direction vector that represents the direction the physics object is facing self.forward=property(fget=lambda self: Vector(1,0).rotate(self.heading)) #This gives an integer that represents how fast the object is moving in the direction it's facing self.fwdspeed=property(fget=lambda self: self.velocity.dot(self.forward)) self.mass=1 

To test it, I wrote this little bit of code:

myphysobj=PhysicsObject() myphysobj.velocity=Vector(15,5) print("Position:",myphysobj.position,"Facing:",myphysobj.forward,"Forward Speed:",myphysobj.fwdspeed) 

I expected the result to be something along these lines:

Position: (0,0) Facing: (0,0) Forward Speed: 5 

However, I instead got

Position: (0,0) Facing: <property object at 0x02AB2150> Forward Speed: <property object at 0x02AB2180> 

As I understand it, setting an attribute to the result of property(fget=myfunc) should give the result of myfunc() when that attribute is accessed. Instead, it seems to be giving me the property object itself. Am I misunderstanding how property() is used, or have I committed a more subtle error?

1 Answer 1

2

property is a descriptor, and descriptors are meant to be defined on the class directly rather than on the instance.

class PhysicsObject: forward = property(fget=lambda self: Vector(1,0).rotate(self.heading)) fwdspeed = property(fget=lambda self: self.velocity.dot(self.forward)) def __init__(...): ... 
Sign up to request clarification or add additional context in comments.

4 Comments

Well, I tried that, but now myphysicsobject.forward gives None. Any idea what's going on there? It's also worth noting that the link to the python docs you have is to the 2.7.x edition, while this question is tagged as 3.x.
It returns None because the Vector.rotate() method operates in place. The descriptor protocol hasn't changed between 2.x and 3.x.
Wait, does Python come with a Vector class in one of the standard libraries? I wrote my own (whose rotate() also operates in-place, but I didn't intend for it to do so).
It does not. I inferred it by the behavior you described.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.