美文网首页
描述符的运用

描述符的运用

作者: 超人不会飞_9664 | 来源:发表于2018-12-16 13:26 被阅读0次

    描述符

    描述符就是一个类,一个至少拥有get(self,instance,owner),set(self,instance,value),delete(self,instance) 三个方法的任意一个或几个

    • get(self,instance,owner)
      用于访问属性,它返回属性的值
    • set(self,instance,value)
      属性被赋值中调用,不返回任何值
    • delete(self,instance)
      控制删除操作,不返回任何内容
    >>> class MyDecriptor:
        def __get__(self,instance,owner):
            print('getting',self,instance,owner)
        def __set__(self,instance,value):
            print('setting',self,instance,value)
        def __delete__(self,instance):
            print('deleting',self,instance)
    
        
    >>> class Test():
        x = MyDecriptor()
    
        
    >>> text = Test()
    >>> text.x
    getting <__main__.MyDecriptor object at 0x000001B84F911E80> <__main__.Test object at 0x000001B84F8989E8> <class '__main__.Test'>
    >>> text.x = 'love'
    setting <__main__.MyDecriptor object at 0x000001B84F911E80> <__main__.Test object at 0x000001B84F8989E8> love
    >>> del text.x
    deleting <__main__.MyDecriptor object at 0x000001B84F911E80> <__main__.Test object at 0x000001B84F8989E8>
    >>> text
    <__main__.Test object at 0x000001B84F8989E8>
    >>> Test
    <class '__main__.Test'>
    

    注意instance(拥有者的实例对象) 是Test()的实例化对象test, owner 是Test

    自己定义一个 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)
        def __set__(self,instance,value):
            self.fset(instance,value)
        def __delete__(self,instance):
            self.fdel(instance)
    
    
    class C:
        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)
    c = C()
    
    c.x=1
    print(c._x)
    
    1
    

    先定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性

    class Celsius:
        def __init__(self,value = 26.0):
            self.value = value
        def __get__(self, instance, owner):
            return self.value
        def __set__(self, instance, value):
            self.value = 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 = 100
    print(temp.cel)
    
    temp.fah = 70
    print(temp.cel)
    print(temp.fah)
    
    26.0
    100
    21.11111111111111
    70.0
    

    相关文章

      网友评论

          本文标题:描述符的运用

          本文链接:https://www.haomeiwen.com/subject/gtdtkqtx.html