我想在类中定义该类的静态空实例,以在某些函数中用作默认值:
class Pref(object):
def __init__(self,a,b):
...
__dummy = Pref(None,None)
...
def combine(self, other_pref=__dummy):
...
但是,这会给出一个错误,即Pref未定义。
这样做的正确方法是什么?
答案 0 :(得分:1)
以下是实现它的一种方法,使用类方法初始化类属性:
class Pref(object):
_dummy = None
def __init__(self, a, b):
...
@classmethod
def dummy(cls):
if cls._dummy is None:
cls._dummy = cls(None, None)
return cls._dummy
def combine(self, other_pref=None):
if other_pref is None:
other_pref = self.dummy()
...
...
请注意代码样式的更改,按the style guide。