我是python的新手,目前正在尝试学习属性。
class Car(object):
def set_speed(self, speed):
self._speed = speed
print("set speed to {}".format(self.speed))
def get_speed(self):
return self._speed
print("the speed is {}".format(self.speed))
speed = property(fget = get_speed, fset=set_speed)
car1 = Car()
car1.speed = 170
x = car1.speed
我得到的输出是set speed to 170
这一切都很好,而且自car1.speed
被召唤以来就没有任何意外。但是,为什么从来没有"The speed is 170"
印刷品?
car1.speed
以同样的方式被召唤?有没有我不理解的东西?
答案 0 :(得分:7)
您在<{em> return
电话之前使用了print()
语句。此时函数执行结束,永远不会达到print()
:
def get_speed(self):
# return ends a function
return self._speed
# anything beyond this point is ignored
print("the speed is {}".format(self.speed))
将print()
调用放在返回语句之前:
def get_speed(self):
print("the speed is {}".format(self._speed))
return self._speed
我更正了print()
函数以显示self._speed
( 属性名称中的下划线),否则您将进入无限递归(自{ {1}}将再次触发该属性getter)。您可能希望在self.speed
函数中执行相同操作,因为它也会触发set_speed()
getter,并且您会在get_speed()
之前看到the speed is <newspeed>
打印每次更改速度时都会打印:
set speed to <newspeed>
接下来,您可以将class Car(object):
def set_speed(self, speed):
self._speed = speed
print("set speed to {}".format(speed))
def get_speed(self):
print("the speed is {}".format(self._speed))
return self._speed
speed = property(fget = get_speed, fset=set_speed)
对象用作装饰器;生成的property
实例有一个property
方法,然后可以重新使用它来装饰setter:
setter()
请参阅How does the @property decorator work?,了解其运作方式。