class_new.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. try:
  2. # If we don't expose object.__new__ (small ports), there's
  3. # nothing to test.
  4. object.__new__
  5. except AttributeError:
  6. print("SKIP")
  7. raise SystemExit
  8. class A:
  9. def __new__(cls):
  10. print("A.__new__")
  11. return super(cls, A).__new__(cls)
  12. def __init__(self):
  13. print("A.__init__")
  14. def meth(self):
  15. print('A.meth')
  16. #print(A.__new__)
  17. #print(A.__init__)
  18. a = A()
  19. a.meth()
  20. a = A.__new__(A)
  21. a.meth()
  22. #print(a.meth)
  23. #print(a.__init__)
  24. #print(a.__new__)
  25. # __new__ should automatically be a staticmethod, so this should work
  26. a = a.__new__(A)
  27. a.meth()
  28. # __new__ returns not an instance of the class (None here), __init__
  29. # should not be called
  30. class B:
  31. def __new__(self, v1, v2):
  32. print("B.__new__", v1, v2)
  33. def __init__(self, v1, v2):
  34. # Should not be called in this test
  35. print("B.__init__", v1, v2)
  36. print("B inst:", B(1, 2))
  37. # Variation of the above, __new__ returns an instance of another class,
  38. # __init__ should not be called
  39. class Dummy: pass
  40. class C:
  41. def __new__(cls):
  42. print("C.__new__")
  43. return Dummy()
  44. def __init__(self):
  45. # Should not be called in this test
  46. print("C.__init__")
  47. c = C()
  48. print(isinstance(c, Dummy))