zoukankan      html  css  js  c++  java
  • Python ————反射机制

    python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

    # commons.py 文件
     
    name = "nick"
     
    def f1():
        return "This is f1."
     
    def f2():
        return "This is f2."
     
    def nb():
        return "This is niubily."
     
     
     
    # index.py 文件
    import commons
     
    #根据字符串的形式去某个模块中寻找东西
    target_func = getattr(commons,"f1")     # 找函数
    result = target_func()
    print(result)
     
    target_func = getattr(commons,"name")   # 找全局变量
    print(target_func)
     
    target_func = getattr(commons,"age",None)   # 找不到返回None
    print(target_func)
     
    #根据字符串的形式去某个模块中判断东西是否存在
    tarhas_func = hasattr(commons,"f5")     # 找函数
    print("before:",tarhas_func)
     
    # tarhas_func = hasattr(commons,"name") # 找全局变量
    # print(tarhas_func)
     
    #根据字符串的形式去某个模块中设置东西
    setattr(commons,"f5","lambda x: return "This is new func."")  # 设置一个函数
    setattr(commons,"age",18)       # 设置全局变量
     
    tarhas_func = hasattr(commons,"f5")     # 检查函数是否存在
    print("after:",tarhas_func)
     
    #根据字符串的形式去某个模块中删除东西
    delattr(commons,"f5")       # 删除一个函数
     
    tarhas_func = hasattr(commons,"f5")     # 检查函数是否存在
    print("end:",tarhas_func)

    对象实例

    class Foo:
       def __init__(self,name,age):
           self.name=name
           self.age=age
    
       def show(self):
            print("获取到了该函数方法")
    
    obj=Foo('2018世界杯',2018)
     #hasattr 是否存在字段
    print(hasattr(obj,'name'))
    #getattr获取信息
    getname=getattr(obj,'name')
    print(getname)
    #setattr赋值
    setattr(obj,'time','2018-6-16')
    print(obj.time)
    #delattr删除
    delattr(obj,'name')
    print(obj.name)#删除后报错AttributeError: 'Foo' object has no attribute 'name'
  • 相关阅读:
    Handling Touches
    Learn the Basics
    Getting started
    (dev mode) install CONSUL on ubuntu
    Resilience4j usage
    spring cloud gateway
    courator
    courator
    js 获取服务器控件
    js
  • 原文地址:https://www.cnblogs.com/lanyinhao/p/9197503.html
Copyright © 2011-2022 走看看