属性访问 property
class C: def __init__(self, size=10): self.size = size def getSize(self): return self.size def setSize(self, value): self.size = value def delSize(self): del self.size x = property(getSize, setSize, delSize) c = C() c.x = 1 print(c.size)
定义一个矩形
class Rectangle(): def __init__(self, width=0, hight=0): self.width = width self.hight = hight def __setattr__(self, name, value): if name == 'Square': self.hight = value self.width = value else: super().__setattr__(name, value) def getArea(self): return self.width * self.hight r1 = Rectangle(3,6) print(r1.getArea()) r1.Square =10 print(r1.getArea())
如果不使用super()访问基类的方法,就会陷入死循环
描述符:将某种特殊类型的类的实例指派给另一个类的属性
练习:要求定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性。要求两个属性会自动进行转换。
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() temp.cel = 30 print(temp.fah) print('*') temp.fah = 100 print(temp.cel)
输出结果是
86.0
*
37.77777777777778
能够实现华氏温度和摄氏温度的互相转换