18

According to the docs,

__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument.

It explicitly isn't a classmethod, but generally looks like one, except that any client manually calling __new__ needs to do explicitly pass in the class argument. For example:

>>> str.__new__()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    str.__new__()
TypeError: str.__new__(): not enough arguments
>>> str.__new__(str)
''

But alternate object creation APIs - eg, all eight alternate datetime constructors - are usually classmethods, so that datetime.now() works as expected.

Why is __new__ set up this way?

lvc
  • 34,233
  • 10
  • 73
  • 98
  • 2
    Maybe because not being a classmethod allows you to do something like `BaseClass.__new__(DerivedClass)`. – interjay Mar 01 '15 at 09:55
  • 3
    It can be useful in metaclasses or when we override an immutable object, because in those cases we call it using: `type.__new__(meta, ...)` and `float.__new__(NewFloat, ...)` – Ashwini Chaudhary Mar 01 '15 at 09:59
  • 1
    @AshwiniChaudhary but the only time you would use that is inside `NewFloat.__new__`, where `super().__new__(...)` would do the right thing. Also, why would that logic not apply to overridden alternate constructors? – lvc Mar 01 '15 at 10:10
  • 1
    I think i've understood: two different class "arguments" would not be needed if Python could [cast instances of a base class into instances of a derived class](https://stackoverflow.com/q/3464061). If it was possible, then, after calling the ancestor class' `__new__` from the descendant class' `__new__`, one could cast the returned instance into the descendant type. As this seems impossible (in an unhackish way), the ancestor's `__new__` should be able to return the descendant's instance. – Alexey Feb 23 '18 at 17:16
  • It seems weird that it is not a class method, though. Is it mildly prohibited to use from `__new__` the class where it is defined? – Alexey Feb 23 '18 at 17:20

0 Answers0