反射(hasattr,getattr,delattr,setattr)

反射(hasattr,getattr,setattr,delattr)

Use reflection class

  • It is reflected to the operation by the object class or string property
  • Essentially reflected in the use of built-in functions, wherein the reflector has four built-in functions:
  1. hasattr: determining whether there is a method in the class
  2. getattr: character string to the last memory address of the corresponding method in the object obj, plus '()' can be performed in parentheses
  3. setattr: setattr the outside by a function bound to the instance
  4. delattr: Delete a class or instance method
class People:
    country = 'China'

    def __init__(self, name):
        self.name = name

    def eat(self):
        print('%s is eating' % self.name)


peo1 = People('egon')
print(hasattr(peo1,'eat')) #True

print(getattr(peo1,'eat')) #<bound method People.eat of <__main__.People object at 0x1043b9f98>>

print(getattr(peo1,'xxxxx',None)) #None

setattr(peo1,'age',18) #peo.age=18
print(peo.age) #18
print(peo1.__dict__) #{'name':'egon','age':18}

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

application

Requirements: Enter the command to start the function by user

lass Ftp:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    def get(self):
        print('GET function')

    def put(self):
        print('PUT function')

    def run(self):
        while True:
            choice = input('>>>: ').strip()

            if choice == 'q':
                print('break')
                break


#             print(choice, type(choice))
#             if hasattr(self, choice):
#                 method = getattr(self, choice)
#                 method()
#             else:
#                 print('输入的命令不存在')

            method = getattr(self, choice, None)

            if method is None:
                print('输入的命令不存在')
            else:
                method()
conn = Ftp('1.1.1.1', 23)
conn.run()

######
>>>: time
输入的命令不存在
>>>: time
输入的命令不存在
>>>: q
break

Reflected in module

We want to import another module, you can use the import now there is such a demand, I enter a dynamic module name, you can access the method or variable import module at any time, you can do so:

imp = input(“请输入你想导入的模块名:”)
CC = __import__(imp) 這种方式就是通过输入字符串导入你所想导入的模块 
CC.f1()  # 执行模块中的f1方法

Although this method can be custom import module, but the method is performed is fixed, the dynamic password if required, can be:

# dynamic.py
imp = input("请输入模块:")
dd = __import__(imp)
# 等价于import imp
inp_func = input("请输入要执行的函数:")

f = getattr(dd, inp_func,
            None)  # 作用:从导入模块中找到你需要调用的函数inp_func,然后返回一个该函数的引用.没有找到就返会None

f()  # 执行该函数
请输入模块:time
请输入要执行的函数:time

1560959528.6127071

Reflection

In fact reflected by a string, import module; by a string, to find the specified function module, and execute. Use a string to an object (module) in operation (Find / get / delete / add) a member of a string-based, event-driven

getattr()

getattr () function is a function of introspection python

class A:
    def __init__(self):
        self.name = 'nick'
        # self.age='18'

    def method(self):
        print("method print")


a = A()

print(getattr(a, 'name',
              'not find'))  # 如果a 对象中有属性name则打印self.name的值,否则打印'not find'
print(getattr(a, 'age',
              'not find'))  # 如果a 对象中有属性age则打印self.age的值,否则打印'not find'
print(getattr(a, 'method', 'default'))  # 如果有方法method,打印其地址,否则打印default
print(getattr(a, 'method', 'default')())  # 如果有方法method,运行函数并打印None否则打印default

hasattr(object,name)

Determine whether the target object contains properties named name (hasattr time whether an exception is thrown by calling getattr (object, name) to achieve)

setattr(object,name,value)

This is the corresponding getattr (). Parameter is an object, a string and an arbitrary value. The string may be listed in an existing property or a new property. This function assigns a value to the property. This object allows it provides. For example, setattr (x, "foobar", 123) corresponding to x.foobar = 123.

delattr(object,name)

A set of functions related setattr (). Parameter is an object (remember python, everything is an object) and a string composed. The string argument must be one of the object property name. This function deletes a specified by the obj string attribute. delattr (x, 'foobar') = del x.foobar

With the above four functions, to perform a series of operations of the modules.

r = hasattr(commons, xxx,'not find')  # 判断某个函数或者变量是否存在
print(r)

setattr(commons, 'age', 18)  # 给commons模块增加一个全局变量age = 18,创建成功返回none

setattr(commons, 'age', lambda a: a + 1)  # 给模块添加一个函数

delattr(commons, 'age')  # 删除模块中某个变量或者函数

Guess you like

Origin www.cnblogs.com/zhoajiahao/p/11068070.html