object_new.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # object.__new__(cls) is the only way in Python to allocate empty
  2. # (non-initialized) instance of class.
  3. # See e.g. http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html
  4. # TODO: Find reference in CPython docs
  5. try:
  6. # If we don't expose object.__new__ (small ports), there's
  7. # nothing to test.
  8. object.__new__
  9. except AttributeError:
  10. print("SKIP")
  11. raise SystemExit
  12. class Foo:
  13. def __new__(cls):
  14. # Should not be called in this test
  15. print("in __new__")
  16. raise RuntimeError
  17. def __init__(self):
  18. print("in __init__")
  19. self.attr = "something"
  20. o = object.__new__(Foo)
  21. #print(o)
  22. print("Result of __new__ has .attr:", hasattr(o, "attr"))
  23. print("Result of __new__ is already a Foo:", isinstance(o, Foo))
  24. o.__init__()
  25. #print(dir(o))
  26. print("After __init__ has .attr:", hasattr(o, "attr"))
  27. print(".attr:", o.attr)
  28. # should only be able to call __new__ on user types
  29. try:
  30. object.__new__(1)
  31. except TypeError:
  32. print("TypeError")
  33. try:
  34. object.__new__(int)
  35. except TypeError:
  36. print("TypeError")