**描述符就是将某种特殊类型的类的实例指派给另一个类的属性**<br />**___get__(self, instance, owner)用于访问属性,它返回属性的值**
set(self, instance, value)将在属性分配操作中调用, 不返回任何内容
delete(self, instance)控制删除,不返回任何内容
自带的 Property
class MyDecriptor:
def __get__(self, instance, owner):
print("getting...", instance, owner)
def __set__(self, instance, value):
print("setting...", instance, value)
def __delete__(self, instance):
print("deleteting...", instance)
class Test:
x = MyDecriptor()
test = Test()
test.x
test.x = "100"
del test.x
--------------------------------
getting... <__main__.Test object at 0x0316B040> <class '__main__.Test'>
setting... <__main__.Test object at 0x0316B040> 100
deleteting... <__main__.Test object at 0x0316B040>
自已实现 Property
class MyProperty:
def __init__(self, fget = None, fset = None, fdel = None):
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self, instance, owner):
return self.fget(instance) # instance 实例对象
def __set__(self, instance, value):
return self.fset(instance, value)
def __delete__(self, instance):
return self.fdel(instance)
class Test:
def __init__(self):
self._x = None
def getX(self):
return self._x
def setX(self, value):
self._x = value
def delX(self):
del self._x
x = MyProperty(getX, setX, delX)
test = Test()
test.x = "x-main"
print(test.x) # 用x 取修改了 _x 的值 _x 属于另一个的的属性
print(test._x)
------------------------------------
x-main
x-main
练习要求
先定义一个温度类, 然后定义两个描述符类 用于描述摄氏度和华氏度两个属性 .
要求两个属性会自动进行转换, 也就是说你可以给摄氏度这个属性赋值, 然后打印的华氏度属性是自动转换后的结果
公式: * 1.8 + 32
class Celsius:
def __init__(self, value = 26.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
class Fahrenheit:
def __get__(self, instance, owner):
return instance.cel *1.8+32
def __set__(self, instance, value):
instance.cel = (float(value) - 32) / 1.8
class Temperature:
cel = Celsius()
fah = Fahrenheit()
temp = Temperature()
print(temp.cel) # 默认是摄氏度
temp.cel = 30 # 修改摄氏度
print(temp.fah) # 自动转换为华氏度
temp.fah = 100 # 输入华氏度
print(temp.cel) # 自动转换摄氏度
-------------------------------
26.0
86.0
37.77777777777778