简要上下文:我正在尝试将类的默认参数编辑为其 __new__
方法。我需要访问该方法,并且我试图以与访问其其他方法相同的方式获得访问权 - 通过其 __dict__
。
但是在这里,我们可以看到它的 __new__
方法不在它的 __dict__
中。
这与 __new__
是静态方法有关吗?如果是这样,为什么不在类的 __dict__
中?它们存储在对象模型中的什么位置?
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__.A.f>
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'] == A.f
Out[17]: True
最佳答案
A.__dict__['new']
是静态方法描述符,其中 as A.__new__
是实际的底层函数。
https://docs.python.org/2/howto/descriptor.html#static-methods-and-class-methods
如果您需要调用该函数,或使用字符串获取它(在运行时),请使用 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>
关于python - 为什么一个类的 __new__ 方法不在它的 __dict__ 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158219/