简介
1 魔术方法
反射就是通过字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员。
魔法方法 | 简介 |
---|---|
getattr | 根据字符串去某个模块中寻找方法 |
hasattr | 根据字符串去判断某个模块中该方法是否存在 |
setattr | 根据字符串去某个模块中设置方法 |
delattr | 根据字符串去某个模块中删除方法 |
2 使用示例
- getattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect
def function_test():
print("function_test")
class Person(object):
def __init__(self,name ):
self.name = name
def set_age(self,age):
self.age = age
def __str__(self):
return "Class Person name:%s id:%s"%(self.name, id(self))
if __name__ == '__main__':
person1 = Person("xiaowang")
print(getattr(person1,'name')) #从类中获得属性
fun = getattr(person1,'set_age') #从类中获得方法
if fun:
fun(18)
print(person1.age)
print(person1)
'''
xiaowang
18
Class Person name:xiaowang id:1862869258192
'''
- hasattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect
def function_test():
print("function_test")
class Person(object):
def __init__(self,name ):
self.name = name
def set_age(self,age):
self.age = age
def __str__(self):
return "Class Person name:%s id:%s"%(self.name, id(self))
if __name__ == '__main__':
person1 = Person("xiaowang")
print(hasattr(person1,'set_age'))
print(hasattr(person1, 'name'))
print(hasattr(person1, 'age'))
person1.set_age(18)
print(hasattr(person1, 'age'))
'''
True
True
False
True
'''
- setattr和 delattr
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Zero
import sys
import inspect
def function_test():
print("function_test")
class Person(object):
def __init__(self,name ):
self.name = name
def set_age(self,age):
self.age = age
def __str__(self):
return "Class Person name:%s id:%s"%(self.name, id(self))
if __name__ == '__main__':
person1 = Person("xiaowang")
setattr(person1,'name',"小明")
setattr(person1,'age', 19)
setattr(person1, 'sex', "man")
print(person1)
print(person1.age, person1.sex)
print(hasattr(person1, 'sex'))
delattr(person1, 'sex')
print(hasattr(person1,'sex'))
'''
Class Person name:小明 id:1683276389728
19 man
True
False
'''
注:getattr,hasattr,setattr,delattr对模块的修改都在内存中进行,并不会影响文件中真实内容。
3 应用场景
- 1 动态加载模块,固定目录加载插件一样写工具。