如果我要动态地向本地模块添加属性(在该模块中添加属性),首选哪两种方式?为什么?我想让它适用于Python 2和3以及未来的3.x。
1
# cat ./test1.py
import sys
def set_attr(name, value):
this = sys.modules[__name__]
setattr(this, name, value)
if __name__ == "__main__":
set_attr("get_doubled", lambda x: x * 2)
set_attr("get_tripled", lambda x: x * 3)
print(get_doubled(1))
print(get_tripled(1))
# python ./test1.py
2
3
2
# cat ./test2.py
def set_attr(name, value):
globals()[name] = value
if __name__ == "__main__":
set_attr("get_doubled", lambda x: x * 2)
set_attr("get_tripled", lambda x: x * 3)
print(get_doubled(1))
print(get_tripled(1))
# python ./test2.py
2
3
答案 0 :(得分:0)
可能会有一点差别。检查一下:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
def set_attr(name, value):
this = sys.modules[__name__]
setattr(this, name, value)
def set_attr1(name, value):
globals()[name] = value
def test():
set_attr("get_doubled", lambda x: x * 2)
set_attr("get_tripled", lambda x: x * 3)
def test1():
set_attr1("get_doubled", lambda x: x * 2)
set_attr1("get_tripled", lambda x: x * 3)
if __name__ == "__main__":
import timeit
print timeit.timeit("test()", "from __main__ import test") # 2.304...
print timeit.timeit("test1()", "from __main__ import test1") # 1.201...
复杂性必须不同。我想,细节应该检查源代码。所以,我更喜欢第二种方式。