getattr用来获取某个类中的变量或函数
setattr则可以动态修改、增加某个类的变量或函数
代码一目了然
Python 2.7.10 (default, Sep 14 2015, 02:26:06)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class test(object):
... def __init__(self):
... self.attr1 = "attr_1"
... self.attr2 = "attr_2"
... def method1(self, output):
... print output
...
>>> t = test()
>>> print getattr(t, "attr1")
attr_1
>>> print getattr(t, "attr2")
attr_2
>>> print getattr(t, "attr3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'test' object has no attribute 'attr3'
>>> print getattr(t, "method1")
<bound method test.method1 of <__main__.test object at 0x10ceae510>>
>>> b = getattr(t, "method1")
>>> b("fuck")
fuck
>>> setattr(t, "attr3", "attr_3")
>>> getattr(t, "attr3")
'attr_3'
>>> getattr(t, "attr4")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'test' object has no attribute 'attr4'
>>> getattr(t, "attr4", "default_attr4")
'default_attr4'
>>> setattr(t, "method2", t.method1)
>>> b = getattr(t, "method2")
>>> b("fuck")
fuck