简要说明:我尝试编辑类__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
答案 0 :(得分:2)
A.__dict__['new']
是staticmethod描述符,其中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>