littlely
littlely

Reputation: 1428

Why it only realize the last instance when using python singleton pattern

the code is in belows:

class A(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance

    def __init__(self, book):
        self.book = book

    def pr(self):
        print(self.book)


if __name__ == "__main__":
    b = A("wind")
    a = A("good")
    print(a is b)
    print(a.pr())
    print(b.pr())

the result is

True
good
None
good
None
why the result is not:

True
wind
good

where is wrong with the code?

Upvotes: 0

Views: 34

Answers (1)

georgexsh
georgexsh

Reputation: 16624

for each time of call A(), its __init__ will be invoked, as it is a singleton, the __init__() method invoked twice on the same object. you could get your expected result with:

b = A("wind")
b.pr()
a = A("good")
a.pr()
print(a is b)

Upvotes: 2

Related Questions