我刚写了这堂课:
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
为了测试它,我写了一些代码:
myphysobj=PhysicsObject()
myphysobj.velocity=Vector(15,5)
print("Position:",myphysobj.position,"Facing:",myphysobj.forward,"Forward Speed:",myphysobj.fwdspeed)
我希望结果可以是这样的:
Position: (0,0) Facing: (0,0) Forward Speed: 5
然而,我反而得到了
Position: (0,0) Facing: <property object at 0x02AB2150> Forward Speed: <property object at 0x02AB2180>
据我了解,将属性设置为property(fget=myfunc)
的结果应该在访问该属性时给出myfunc()
的结果。相反,它似乎给了我属性对象本身。我误解了property()
是如何使用的,还是我犯了一个更微妙的错误?
答案 0 :(得分:2)
property
是descriptor,描述符应该直接在类上定义,而不是在实例上定义。
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__(...):
...