fork download
  1. class A:
  2. def __init__(self, s):
  3. self.s = s
  4. def __eq__(self, other):
  5. return self.s == other.s
  6. print(A("string") == A("string")) # True
  7. print(A("string") is A("string")) # False
  8.  
  9. class B(A):
  10. pool = {} # вообще это должен быть WeakValueDictionary,
  11. # иначе пул будет препятствовать уничтожению объектов GC
  12. def __new__(cls, s):
  13. existing = B.pool.get(s, None)
  14. if existing: return existing
  15. result = super().__new__(cls)
  16. B.pool[s] = result
  17. return result
  18. print(B("string") == B("string")) # True
  19. print(B("string") is B("string")) # True
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
True
False
True
True