我的程序使用MethodType
向类添加方法。问题在于,当代码试图访问属性时,它会获取属性对象,而不是属性值。代码如下:
#!/usr/bin/env python3
from types import MethodType
from ev3dev2.sensor import *
from ev3dev2.sensor.lego import LightSensor
# methods that extend the class
def set_calibration(self,min_value,max_value):
self.min_value = min_value
self.max_value = max_value
self.value_range = max_value - min_value
def read_calibrated(self):
value = self.reflected_light_intensity
print(value)
return 100 * ( value - self.min_value ) / self.value_range
LightSensor.set_calibration = MethodType( set_calibration, LightSensor )
LightSensor.read_calibrated = MethodType( read_calibrated, LightSensor )
# create class instance
light_left = LightSensor(INPUT_2)
light_left.set_calibration( 20, 60 )
print(light_left.reflected_light_intensity)
print(light_left.read_calibrated())
当我运行程序时,它会产生以下输出和错误:
59.1
<property object at 0xb69f3fc0>
Traceback (most recent call last):
File "./property_test.py", line 27, in <module>
print(light_left.read_calibrated())
File "./property_test.py", line 17, in read_calibrated
return 100 * ( value - self.min_value ) / self.value_range
TypeError: unsupported operand type(s) for -: 'property' and 'int'
我也试着用这个:
def read_calibrated(self):
# use underscore to get property value
value = self._reflected_light_intensity
print(value)
return 100 * ( value - self.min_value ) / self.value_range
但这产生了一个错误:AttributeError: type object 'LightSensor' has no attribute '_reflected_light_intensity'
那么,回到原始代码,为什么light_left.reflected_light_intensity
返回一个数字,而self.reflected_light_intensity
返回一个属性对象
更重要的是,如何从read_calibrated()
访问属性值
Python版本是3.5.3
如果要向类而不是实例对象添加方法,只需通过
LightSensor.set_calibration=set_calibration
将其挂钩即可MethodType
用于向类实例添加绑定方法结果:
相关问题 更多 >
编程相关推荐