zoukankan      html  css  js  c++  java
  • python中的描述符

    描述符:含有__set__,__get__,__delete__中的一个或者多个的新式类。
    描述顾名思义,是描述别的类中的属性
    优先级:类属性》数据描述符》实例属性》非数据描述符 (含有__set__与__get__是数据描述符)

    作用: 因为python语言比较自由,比如c++中 int x = 1;可是这里Python x=1就可以,很自由
    有代理作用,类型检测,等等作用

     1 class miaoshufu:
     2     def __init__(self, k, expect_type):  # k是要描述的属性
     3         self.k = k
     4         self.type = expect_type
     5 
     6     def __set__(self, instance, value):  # instance 是实例本身,value是初始化的赋值 ,  owner是拥有它的类
     7         print("---------------set方法")
     8         if type(value) is self.type:
     9             print(instance)
    10             print(value)
    11             instance.__dict__[self.k] = value  # 将这个value这个值真的设置到instance即p这个实例中。这里只能重底层__dict__设置
    12         else:
    13             return print("%s 传入的类型错误" %value) # 用return终止赋值
    14             # raise TypeError
    15 
    16     def __get__(self, instance, owner):  # 这里必须有set,不然优先级靠后,实例前不能检测
    17         print("-------------------get方法")
    18         print(instance)
    19         print(owner)
    20         return instance.__dict__[self.k]
    21 
    22     def __delete__(self, instance):
    23         print("-------del")
    24         instance.__dict__.pop(self.k)
    25 
    26 
    27 class People(object):
    28     name = miaoshufu('name', str)          # 类中name这个属性被上面的描述符描述
    29 
    30     def __init__(self, name, age, salary):
    31         self.name = name
    32         self.age = age
    33         self.salary = salary
    34 
    35 
    36 if __name__ == '__main__':
    37     p = People('wan', 24, 1)          # 触发描述符中的__set__
    38 
    39     p.name = 'li'                     # 触发描述符中的__set__
    40     del p.name
    41     print(p.__dict__)
    View Code
  • 相关阅读:
    IO 单个文件的多线程拷贝
    day30 进程 同步 异步 阻塞 非阻塞 并发 并行 创建进程 守护进程 僵尸进程与孤儿进程 互斥锁
    day31 进程间通讯,线程
    d29天 上传电影练习 UDP使用 ScketServer模块
    d28 scoket套接字 struct模块
    d27网络编程
    d24 反射,元类
    d23 多态,oop中常用的内置函数 类中常用内置函数
    d22 封装 property装饰器 接口 抽象类 鸭子类型
    d21天 继承
  • 原文地址:https://www.cnblogs.com/maxiaonong/p/9498103.html
Copyright © 2011-2022 走看看