关于setattr()函数的思考

一、定义

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.


它可以动态改变任意一个object中属性的行为,像改变某一模块内函数的内容,举个小例子:

reader.py

#!/usr/bin/python
#-*- coding:utf-8 -*-

def index():
    print "in index!"

testtwo.py

#!/usr/bin/python
#-*- coding:utf-8 -*-

from reader import index

def one():
    index()

one()

testone.py

#!/usr/bin/python
#-*- coding:utf-8 -*-

from reader import index
import inspect

def test():
    print "in test!"

setattr(inspect.getmodule(index), index.__name__, test)

print inspect.getmodule(index)

inspect.getmodule(index).index()
index()
from testtwo import one
one()

执行结果为:

可见:在setattr(inspect.getmodule(index), index.__name__, test)执行完之后调用模块index方法的地方会调用test方法.

你可能感兴趣的:(关于setattr()函数的思考)