Python's reflection mechanism

what is reflection

Use the form of a string to operate (find/add/get/delete) members in an object (module), a string-based event-driven.

You can use reflection to dynamically create instances of types, bind types to existing objects, or obtain types from existing objects. Then, you can call the type's methods or access its fields and properties.

Introduction to functions

hasattr(*args, **kwargs):判断对象(模块)中某个函数或者变量是否存在
setattr(x, y, v):给对象(模块)添加一个函数或变量
 getattr(object, name, default=None):获取对象(模块)中的一个函数或变量
delattr(x, y):删除对象(模块)中的一个函数或变量

可以通过 __import__ 方法来导入一个模块

注:hasattr,setattr,delattr 对模块的修改都在内存中进行,并不会影响文件中真实内容

example

__Author__ = "Lance#"

# -*- coding = utf-8 -*-

def default():
    print("This is a default function.")

class Man():
    def __init__(self, name):
        self.__name = name

    def eat(self):
        print("%s is eating ...." % self.__name)

    def age(self):
        print("age is secret")

if __name__ == '__main__':
    m = Man("Lance")

    while True:
        str = input("Please input:")

        if hasattr(m, str):
            func = getattr(m, str)
        else:
            setattr(m, str, default)
            func = getattr(m, str)

        func()

        try:
            delattr(m, str)
            print('Del attr OK')
        except:
            pass
            #print('Can not del method of a class or there is no this attr')

operation result

Please input:age
age is secret
Please input:eat
Lance is eating ....
Please input:height
This is a default function.
Del attr OK

Precautions for using delattr

1. 函数作用用来删除指定对象的指定名称的属性,和 setattr 函数作用相反
2. 当属性不存在的时候,会报错
3. 不能删除对象的方法

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325074285&siteId=291194637