0

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?

2
  • It a is b how should pr() return different values? Commented Nov 23, 2018 at 2:51
  • The wind is the first instance. Why it not True wind wind, Commented Nov 23, 2018 at 2:56

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.