在类中定义虚拟静态变量

时间:2015-10-29 20:45:07

标签: python

我想在类中定义该类的静态空实例,以在某些函数中用作默认值:

class Pref(object):
  def __init__(self,a,b):
      ...

  __dummy = Pref(None,None)

  ...

  def combine(self, other_pref=__dummy):
      ...

但是,这会给出一个错误,即Pref未定义。

这样做的正确方法是什么?

1 个答案:

答案 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