zoukankan      html  css  js  c++  java
  • 反射

    一、什么是反射

    指的是在程序运行过程中可以“动态(不见棺材不落泪)”

    获取对象的信息(数据属性、函数属性)

    静态:在定义阶段就确定类型  

    动态:在调用阶段才去确定类型

    二、为何要用反射

    def func(obj):
        if 'x' not in obj.__dict__:
            return
        obj.x
    
    
    func(10)

    三、实现反射机制的步骤

    1.先通过多dir:查看某一个对象下 可以.出哪些属性来

    print(dir(obj))     #  ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say']

    2.可以通过字符串反射到真正的属性上,得到属性值

     print(obj.__dict__['name']) print(obj.__dict__[dir(obj[-2]]) 

    四、四个内置函数的使用:通过字符串来操作属性值

    1、hasattr()

    1 print(hasattr(obj, 'name'))     # True
    2 print(hasattr(obj, 'x'))        # False

    2、getattr()

    1 print(getattr(obj, 'name'))     # qql
    2 print(getattr(obj, 'x'))        # AttributeError: 'People' object has no attribute 'x'

    3、setattr()

    1 print(getattr(obj, 'name', 'EGON'))     # 修改名字为EGON
    2 print(obj.name)                 # EGON

    4、delattr()

    delattr(obj, 'name')
    print(obj.__dict__)     # {'age': 18}

    获取对象和类

    1 res1 = getattr(obj, 'say')      # obj.say
    2 res2 = getattr(People, 'say')      # People.say
    3 print(res1)     # <bound method People.say of <__main__.People object at 0x0167B0B8>>
    4 print(res2)     # <function People.say at 0x016783D0>

    查看是否有这个方法

     1 obj = 10
     2 if hasattr(obj, 'x'):
     3     print(getattr(obj, 'x'))
     4 else:
     5     print('找不到')      # 找不到
     6 
     7 print(getattr(obj, 'x', None))   # None
     8 
     9 print(getattr(People, 'say', None))   # <function People.say at 0x01AC83D0>
    10 
    11 if hasattr(obj, 'x'):
    12     setattr(obj, 'x', 1111111)      # 10.x = 1111111
    13 else:
    14     print('找不到')  # 找不到

    基于反射可以十分灵活地操作对象的属性,比如将用户交互的结果反射到具体的功能执行

     1 class Ftp:
     2     def upload(self):
     3         print('正在上传')
     4 
     5     def download(self):
     6         print('正在下载')
     7 
     8     def interactive(self):
     9         method = input('>>>: ').strip()  # method = 'upload'
    10 
    11         if hasattr(self, method):
    12             getattr(self, method)()
    13 
    14         else:
    15             print('该指令不存在!')
    16 
    17 
    18 obj = Ftp()
    19 obj.interactive()
    每天逼着自己写点东西,终有一天会为自己的变化感动的。这是一个潜移默化的过程,每天坚持编编故事,自己不知不觉就会拥有故事人物的特质的。 Explicit is better than implicit.(清楚优于含糊)
  • 相关阅读:
    1.计算机初识
    re模块前瞻后顾 快速
    getattr 对类使用
    sklearn iris快速
    numpy c_
    sorted函数 字典按值倒序 实现
    logging快速入门
    configparser快速应用
    reduce 和 map 函数
    一个简单的类继承
  • 原文地址:https://www.cnblogs.com/kylin5201314/p/13621082.html
Copyright © 2011-2022 走看看