Why is there no __new__ class in the __dict__ class?

Short context: I'm trying to edit the default class arguments to its __new__ method. I need access to the method, and I tried to access in the same way as I got access to its other methods - through its __dict__ .

But here we see that his __new__ method __new__ not in __dict__ .

Is this __new__ to the __new__ static method? If so, why is it not in the __dict__ class? Where are they stored in the object model?

 class A(object): def __new__(cls, a): print(a) return object.__new__(cls) def f(a): print(a) ....: In [12]: A.__dict__['f'] Out[12]: <function __main__.Af> In [13]: A.__dict__['__new__'] Out[13]: <staticmethod at 0x103a6a128> In [14]: A.__new__ Out[14]: <function __main__.A.__new__> In [16]: A.__dict__['__new__'] == A.__new__ Out[16]: False In [17]: A.__dict__['f'] == Af Out[17]: True 
+5
source share
1 answer

A.__dict__['new'] is a staticmethod handle, where as A.__new__ is the actual base function.

https://docs.python.org/2/howto/descriptor.html#static-methods-and-class-methods

if you need to call a function or get it using a string (at runtime), use getattr(A, '__new__')

 >>> A.__new__ <function A.__new__ at 0x02E69618> >>> getattr(A, '__new__') <function A.__new__ at 0x02E69618> 

Python 3.5.1

 class A(object): def __new__(cls, a): print(a) return object.__new__(cls) def f(a): print(a) >>> A.__dict__['__new__'] <staticmethod object at 0x02E66B70> >>> A.__new__ <function A.__new__ at 0x02E69618> >>> object.__new__ <built-in method __new__ of type object at 0x64EC98E8> >>> A.__new__(A, 'hello') hello <__main__.A object at 0x02E73BF0> >>> A.__dict__['__new__'](A, 'hello') Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> TypeError: 'staticmethod' object is not callable >>> getattr(A, '__new__') <function A.__new__ at 0x02E69618> 
+2
source

Source: https://habr.com/ru/post/1233812/


All Articles