我希望能够访问指向类max
中指定的内部属性Room
的行为。
>>> r = Room()
>>> r.temperature
22.0
>>> r.temperature = 18.0
>>> r.temperature.max
30.0
>>> r.temperature
18.0
我想用这个最小的代码来解决这个问题:
class Room(object):
@inner_property('min', get_temperature_min)
@inner_property('max', get_temperature_max)
def temperature(self):
'''The temperature of the room'''
return get_temperature()
但是目前,我只能使用以下代码成功实现此行为:
class Room(object):
__init_done = False
def __init__(self):
self.temperature = "shadow"
self.__init_done = True
def __getattribute__(self, attr):
if attr is 'temperature':
return FloatMinMax(get_temperature(),
get_temperature_min(), get_temperature_max(),
'Room temperature')
return super(Room, self).__getattribute__(attr)
def __setattr__(self, attr, value):
if attr is not 'temperature' or self.__init_done is False:
super(Room, self).__setattr__(attr, value)
else:
set_temperature(value)
class FloatMinMax(float):
def __new__(cls, value, min_, max_, doc_):
return super(FloatMinMax, cls).__new__(cls, value)
def __init__(self, value, min_, max_, doc_):
self.__min = min_
self.__max = max_
self.__doc__ = doc_
super(FloatMinMax, self).__init__()
@property
def min(self): return self.__min
@property
def max(self): return self.__max
如何使用装饰器简化写作?