【问题标题】:How make a singleton using Python? [duplicate]如何使用 Python 制作单例? [复制]
【发布时间】:2016-03-05 00:18:44
【问题描述】:

我正在尝试制作单音模式:

class Room:
    obj = None 

    def __new__(cls):          
        if cls.obj is None:               
            cls.obj = object.__new__(cls) 
        return cls.obj   

    def __init__(self, left_wall, right_wall, front_wall, back_wall):
        self.left_wall = left_wall
        self.right_wall = right_wall
        self.front_wall = front_wall
        self.back_wall = back_wall

    def __str__(self):
        return str(self.left_wall) + str(self.right_wall) + str(self.front_wall) + str(self.back_wall)


room_obj = Room(True, False, True, True)
print(room_obj)

room_obj2 = Room(True, False, False, True)
print(room_obj2)

print(room_obj is room_obj2)

运行此代码后,在控制台中得到以下信息:

kalinin@kalinin ~/python/object2 $ python index.py
TrueFalseTrueTrue
TrueFalseFalseTrue
False

它不应该创建两个对象

【问题讨论】:

    标签: python oop design-patterns singleton


    【解决方案1】:

    你可以试试这个,这个例子在http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Singleton.html

    class OnlyOne:
        class __OnlyOne:
            def __init__(self, arg):
                self.val = arg
            def __str__(self):
                return repr(self) + self.val
        instance = None
        def __init__(self, arg):
            if not OnlyOne.instance:
                OnlyOne.instance = OnlyOne.__OnlyOne(arg)
            else:
                OnlyOne.instance.val = arg
        def __getattr__(self, name):
            return getattr(self.instance, name)
    

    【讨论】:

    • 但这是一个非常艰难的决定)
    • 是的,但你必须关注pattern ;)
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    相关资源
    最近更新 更多