关于oop:如何使用python创建一个singleton?

How make a singleton using Python?

本问题已经有最佳答案,请猛点这里访问。

我想做一个单音模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)

运行此代码后,在控制台中获取以下内容:

1
2
3
4
kalinin@kalinin ~/python/object2 $ python index.py
TrueFalseTrueTrue
TrueFalseFalseTrue
False

它不应该创建两个对象


您可以在http://python-3-patterns-adilms-test.readthedocs.org/en/latest/singleton.html中尝试这个示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)