Python borg模式问题

chr*_*sm1 7 python design-patterns

我在python中实现borg时遇到问题.我在这个问题的答案中找到了一个例子,但它不适合我,除非我遗漏了一些东西.这是代码:


class Config:
    """
    Borg singleton config object
    """
    __we_are_one = {}
    __myvalue = ""

    def __init__(self):
        #implement the borg pattern (we are one)
        self.__dict__ = self.__we_are_one
        self.__myvalue = ""

    def myvalue(self, value=None):
        if value:
           self.__myvalue = value
        return self.__myvalue

conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
Run Code Online (Sandbox Code Playgroud)

我认为这是打印"你好",但对我来说它只是打印一个空白行.任何想法为什么会这样?

Jar*_*die 13

看起来它工作得相当好:-)

问题是,在分配self.__myvalue = ""__init__总是会揍的价值myvalue每一个新的博格是,呃,创造了时间.如果在测试中添加一些额外的打印语句,则可以看到此信息:

conf = Config()
conf.myvalue("Hello")
print conf.myvalue()  # prints Hello
conf2 = Config()
print conf.myvalue()  # prints nothing
print conf2.myvalue() # prints nothing
Run Code Online (Sandbox Code Playgroud)

删除self.__myvalue,事情会没事的.

话虽如此,实施myvalue()有点奇怪.我会说,更好的是使用属性来显式获取getter和setter.如果它还不存在,你还需要一些代码__init__来初始化它的值myvalue,或者至少要处理它在getter中可能不存在的值.也许是这样的:

class Config(object):
    """
    Borg singleton config object
    """
    _we_are_one = {}

    def __init__(self):
        #implement the borg pattern (we are one)
        self.__dict__ = self._we_are_one

    def set_myvalue(self, val):
        self._myvalue = val

    def get_myvalue(self):
        return getattr(self, '_myvalue', None)

    myvalue = property(get_myvalue, set_myvalue)

c = Config()
print c.myvalue # prints None
c.myvalue = 5
print c.myvalue # prints 5
c2 = Config()
print c2.myvalue #prints 5
Run Code Online (Sandbox Code Playgroud)