我已经使用一些全局变量,以保持物体在整个库,例如,可以重复使用相当多的功能:
from some.other.lib import Object1, Object2, Object3, Object4, Object5
def function1(input):
global _object1
try:
_object1
except NameError:
_object1 = Object1
return _object1.func1(input)
def function2(input):
global _object2
try:
_object2
except NameError:
_object2 = Object2
# Use function1 to do something to the input
return _object2.func2(function1(input))
def function3(input):
global _object3
try:
_object3
except NameError:
_object3 = Object3
# Use function1 to do something to the input.
return _object3.func3(function1(input))
def function4(input):
global _object4
try:
_object4
except NameError:
_object4 = Object4
return _object4.func4(input)
def function5(input):
global _object5
try:
_object5
except NameError:
_object5 = Object5
# Use function4 to do something to the input.
return _object5.func5(function4(input))
有没有写这样的装饰,要检查全局变量的代码并不需要手动硬编码为每个的方式function*
?
如类似:
def exist_decorator(_object, _class):
try:
_object
except NameError:
_object = _class
return _object
因此,对于实际的类实现function4()
看起来像:
def function4(input):
global _object4
exist_decorator(_object4, Object4)
return _object4.func4(input)
是这样的语法可能在Python与装饰? 如果没有,怎么我还能创建检查全局变量装饰/缓存?