假设我有一个类
class MyClass(object):
def __init__(self, arg):
self._arg = arg
def execute(self):
# execute business logic
pass
现在,由于我无法控制的原因,我需要在某个地方有一个此类的全局实例。然而,当我定义全局时,我不知道args
应该是什么,所以我只是最初将其设置为None
,然后通过setter定义它。
my_class = None
def set_my_class(arg):
global my_class
my_class = MyClass(arg)
def do_something():
my_class.execute()
好吧,这里有明显的问题。
首先,如果开发人员不调用set_my_class
,那么my_class
仍然是None
,如果我们尝试调用do_something
,我们会得到某种错误。
第二个问题是PyCharm在my_class.execute()
行显示警告,因为None
不包含引用execute
。
因此,我正在寻找如何在这种情况下管理全局并将编译器警告降至最低的想法。如果我在写Java,我只会使用一个接口。但是,我正在寻找一个更Python的解决方案。
将责任委托给类内部。不要用None
分配my_class
,而是用arg=None
创建一个实例。然后,在execute
中,处理未分配的情况。类似于:
class MyClass(object):
def __init__(self, arg=None):
self._arg = arg
def execute(self):
if self._arg is None:
raise ValueError("Didn't assign a proper value")
# execute business logic
pass
my_class = MyClass()
...
此时,您可以直接分配给arg
:,而不是创建新实例并干预global
def set_my_class(arg):
my_class._arg = arg