我想知道如何在不同的函数中访问描述符?当我初始化 Vehicle 类时,我可以将速度初始化为描述符,但是我无法在 Vehicle 函数 (calc_speed()-> self.speed.value) 中访问它的值返回AttributeError: 'int' object has no attribute 'value'
。此外,不应该更改值audi.speed = 120
触发set功能(以及打印应该触发get功能)?
class SpeedDesc(object):
def __init__(self, name, val):
self.var_name = name
self.value = val
def __get__(self, obj, objtype):
print('Getting', self.var_name)
return self.value
def __set__(self, obj, value):
msg = 'Setting {name} to {value}'
print(msg.format(name=self.var_name, value=value))
self.value = value
class Vehicle(object):
def __init__(self, vType):
self.vehicle_type = vType
self.speed = SpeedDesc('speed desc', 100)
def calc_speed(self, accel):
return self.speed.value * accel
if __name__ == '__main__':
audi = Vehicle('sedan')
print('vehicle speed:', audi.speed.value)
audi.speed = 120
print(audi.calc_speed(1.5))
vehicle speed: 100
Traceback (most recent call last):
File "descriptor_example.py", line 31, in <module>
audi.calc_speed(1.5)
File "descriptor_example.py", line 24, in calc_speed
return self.speed.value * accel
AttributeError: 'int' object has no attribute 'value'
我的期望
Getting speed desc
vehicle speed: 100
Setting speed desc to 120
180