Python 3.x Python属性访问会导致属性对象本身
我刚刚写了这节课:Python 3.x Python属性访问会导致属性对象本身,python-3.x,properties,Python 3.x,Properties,我刚刚写了这节课: 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 gi
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>
位置:(0,0)朝向:前进速度:
据我所知,将属性设置为
property(fget=myfunc)
的结果应该在访问该属性时给出myfunc()
的结果。相反,它似乎给了我属性对象本身。我是否误解了如何使用property()
,或者我犯了一个更微妙的错误?property
是一个,描述符应该直接在类上定义,而不是在实例上定义
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__(...):
...
嗯,我试过了,但是现在myphysicsobject.forward没有给出任何结果。知道那里发生了什么吗?还值得注意的是,到python文档的链接是到2.7.x版,而这个问题被标记为3.x。它返回
None
,因为Vector.rotate()
方法在适当的位置运行。描述符协议在2.x和3.x之间没有改变。等等,Python是否在一个标准库中附带了向量类?我自己写的(它的rotate()。我是根据你描述的行为推断出来的。