____tz_zs
getatter()
getattr()这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。
1、从类中获取函数和属性
获取函数
my_getatter.py
import sys
class GetatterTest(object):
def __init__(self):
pass
@staticmethod
def aa():
print("aa staticmethod fun")
def bb(self):
print("bb fun")
cc = "cc attribute"
if __name__ == '__main__':
print(sys.modules[__name__])
print(GetatterTest)
"""
<module '__main__' from '/home/xxx/tzzs/mytz/my_getatter.py'>
<class '__main__.GetatterTest'>
"""
print(getattr(GetatterTest, "aa"))
getattr(GetatterTest, "aa")()
print(getattr(GetatterTest(), "aa"))
getattr(GetatterTest(), "aa")()
"""
<function aa at 0x7f85d5c62c08>
aa staticmethod fun
<function aa at 0x7f85d5c62c08>
aa staticmethod fun
"""
print(getattr(GetatterTest(), "bb"))
getattr(GetatterTest(), "bb")()
"""
<bound method GetatterTest.bb of <__main__.GetatterTest object at 0x7f85e3c4fc50>>
bb fun
"""
获取属性
my_getatter.py
import sys
class GetatterTest(object):
def __init__(self):
pass
@staticmethod
def aa():
print("aa staticmethod fun")
def bb(self):
print("bb fun")
cc = "cc attribute"
if __name__ == '__main__':
print(sys.modules[__name__])
print(GetatterTest)
"""
<module '__main__' from '/home/xxx/tzzs/mytz/my_getatter.py'>
<class '__main__.GetatterTest'>
"""
print(getattr(GetatterTest, "cc"))
print(getattr(GetatterTest(), "cc"))
"""
cc attribute
cc attribute
"""
2、从模块获取类
通过类名字符串得到类对象
my_getatter2.py
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
import sys
import my_getatter
print(sys.modules[__name__]) # <module '__main__' from '/home/xxx/tzzs/mytz/my_getatter2.py'>
# 从模块中获取类对象
class_name = getattr(my_getatter, "GetatterTest")
print(class_name) # <class 'my_getatter.GetatterTest'>
print(class_name()) # <my_getatter.GetatterTest object at 0x7f38a2b36490>
# 调用类的属性和函数,同上例。
print(getattr(class_name, "aa"))
getattr(class_name, "aa")()
print(getattr(class_name(), "aa"))
getattr(class_name(), "aa")()
"""
<function aa at 0x7fd6047edc08>
aa staticmethod fun
<function aa at 0x7fd6047edc08>
aa staticmethod fun
"""
print(getattr(class_name(), "bb"))
getattr(class_name(), "bb")()
"""
<bound method GetatterTest.bb of <my_getatter.GetatterTest object at 0x7fd6128d1490>>
bb fun
"""
print(getattr(class_name, "cc"))
print(getattr(class_name(), "cc"))
"""
cc attribute
cc attribute
"""