Reputation: 1428
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 Nonewhy the result is not:
True wind good
where is wrong with the code?
Upvotes: 0
Views: 34
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