table of Contents
In doing program development, we often encounter such a demand: the need to perform an object in a certain way, or need to call the object a variable, but for various reasons we can not determine the method or variable exists, it is we need to use a special method or mechanism to access and manipulate this unknown method or variable, in which it is called reflex mechanism
Reflection: a string of ways to access the object's properties, methods, call the object , Python are objects in all, you can use reflection .
- hasattr (obj, name): Check whether the object obj contains property or method called name.
- getattr (object, name [, default]): Gets object in the Object attribute called name attribute value.
- setattr (obj, name, value, /): The name attribute of the object obj set value.
Hsattr
Determining whether the object has a method name or attribute name. There are returns True, no returns False
class Person(object):
def __init__(self,name):
self.name = name
def talk(self):
print("%s正在交谈"%self.name)
p = Person("santa")
print(hasattr(p,"talk")) # True。因为存在talk方法
print(hasattr(p,"name")) # True。因为存在name变量
print(hasattr(p,"abc")) # False。因为不存在abc方法或变量
getattr
Acquiring an object property or method, if there is print. hasattr
And getattr
supporting the use of
class Person(object):
def __init__(self,name):
self.name = name
def talk(self):
print("%s正在交谈"%self.name)
p = Person("santa")
n = getattr(p,"name") # 获取name变量的内存地址
print(n) # 此时打印的是:laowang
f = getattr(p,"talk") # 获取talk方法的内存地址
f() # 调用talk方法
# 我们发现getattr有三个参数,那么第三个参数是做什么用的呢?
s = getattr(p,"abc","not find")
print(s)
#若属性不存在,则返回默认值(第三个参数)
Print Results:
Santa
Santa are talking
not find
setattr
After assigning an object to a property, if the property does not exist, create assignments
def abc(self):
print("%s正在交谈"%self.name)
class Person(object):
def __init__(self,name):
self.name = name
p = Person("santa")
setattr(p,"talk",abc) # 将abc函数添加到对象中p中,并命名为talk
p.talk(p) # 调用talk方法,因为这是额外添加的方法,需手动传入对象
#结果
#santa正在交谈
setattr(p,"age",30) # 添加一个变量age,赋值为30
print(p.age) # 打印结果:30
delattr
Delete the object of a specified property. Note: The method can not be used to delete
class Person(object):
def __init__(self,name):
self.name = name
def talk(self):
print("%s正在交谈"%self.name)
p = Person("laowang")
delattr(p,"name") # 删除name变量
print(hasattr(p,'name')) #False
Reflected Application
# 反射应用:
根据用户输入进行动态调用
class FileControl:
def run(self):
while True:
# 让用户输入上传或下载功能的命令:
user_input = input('请输入 上传(upload) 或 下载(download) 功能:').strip()
# 通过用户输入的字符串判断方法是否存在,然后调用相应的方法
if hasattr(self, user_input):
func = getattr(self, user_input)
func()
else:
print('输入有误!')
def upload(self):
print('文件正在上传...')
def download(self):
print('文件正在下载...')
file_control_obj = FileControl()
file_control_obj.run()
This is the reflection of python, in fact, its core essence is to use a string to an object (module) in operation (Find / get / delete / add) members, based on a string of driving events!
__import __ (understand)
If you want to import functions for different directories, you can be: introducing dynamic module
def run():
inp = input("请输入您想访问页面的url: ").strip()
modles, func = inp.split("/")
obj = __import__("lib." + modules, fromlist=True) # 注意fromlist参数 modles是url
if hasattr(obj, func):
func = getattr(obj, func)
func()
else:
print("404")
if __name__ == '__main__':
run()
Thinking:
Some may ask python not have two built-in functions exec and eval it? They also can perform string. such as:
exec("print('haha')")
结果:
haha
So they will not do it directly? Have to try so hard to use getattr, __ import__ doing?
In fact, in the example above, around the central theme is how to use different string-driven events, such as import module, function calls, and so on, these are the reflection of python, is a manifestation of programming, design patterns, the combination of high cohesion, loosely coupled programming ideas, not simply be replaced with a string performed. Of course, exec and eval has its stage, are often used in the web framework.