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
  • 相关阅读:
    Spring中的@Transactional(rollbackFor = Exception.class)属性详解
    查询数据库中表数量和各表中数据量
    69道Spring面试题和答案
    Spring常见面试题总结(超详细回答)
    nginx 解决session一致性
    redis 主从同步
    如何实现一个线程安全的单例,前提是不能加锁
    InnoDB中一棵B+树能存多少行数据
    ConcurrentHashMap 源码分析
    java HashMap 源码解析
  • 原文地址:https://www.cnblogs.com/maxiaonong/p/9498103.html
Copyright © 2011-2022 走看看