zoukankan      html  css  js  c++  java
  • __get__ __set__ __delete__描述符

    描述符就是一个新式类,这个类至少要实现__get__  __set__  __delete__方法中的一种
    class Foo:

    def __get__(self, instance, owner):
    print('__get__')

    def __set__(self, instance, value):
    print('__set__')

    def __delete__(self, instance):
    print('__delete__')

    class fun:
    x = Foo()
    def __init__(self):
    pass


    f = fun()
    f.x #触发__get__
    f.x = 1 #触发__set__
    del f.x #触发__delete__

    2 描述符是干什么的:描述符的作用是用来代理另外一个类的属性的(必须把描述符定义成这个类的类属性,不能定义到构造函数中)

    什么时候用描述符
    #描述符Str
    class Str:
        def __get__(self, instance, owner):
            print('Str调用')
        def __set__(self, instance, value):
            print('Str设置...')
        def __delete__(self, instance):
            print('Str删除...')
    
    #描述符Int
    class Int:
        def __get__(self, instance, owner):
            print('Int调用')
        def __set__(self, instance, value):
            print('Int设置...')
        def __delete__(self, instance):
            print('Int删除...')
    
    class People:
        name=Str()
        age=Int()
        def __init__(self,name,age): #name被Str类代理,age被Int类代理,
            self.name=name
            self.age=age
    
    #何地?:定义成另外一个类的类属性
    
    #何时?:且看下列演示
    
    p1=People('alex',18)
    
    #描述符Str的使用
    p1.name
    p1.name='egon'
    del p1.name
    
    #描述符Int的使用
    p1.age
    p1.age=18
    del p1.age
    
    #我们来瞅瞅到底发生了什么
    print(p1.__dict__)
    print(People.__dict__)
    
    #补充
    print(type(p1) == People) #type(obj)其实是查看obj是由哪个类实例化来的
    print(type(p1).__dict__ == People.__dict__)
    
    

    3 描述符分两种
    一 数据描述符:至少实现了__get__()和__set__()

    1 class Foo:
    2     def __set__(self, instance, value):
    3         print('set')
    4     def __get__(self, instance, owner):
    5         print('get')

    二 非数据描述符:没有实现__set__()

    1 class Foo:
    2     def __get__(self, instance, owner):
    3         print('get')



  • 相关阅读:
    anchor-free : CornerNet 和 CenterNet 简要笔记
    图像分割中的loss--处理数据极度不均衡的状况
    python 装饰器
    python3 新特性
    VSCode Eslint+Prettier+Vetur常用配置
    JS lodash学习笔记
    JS 高端操作整理
    Vue 组件通信
    Vue 搭建vue-element-admin框架
    小程序 HTTP请求封装
  • 原文地址:https://www.cnblogs.com/ajaxa/p/9069005.html
Copyright © 2011-2022 走看看