python - 为什么一个类的 __new__ 方法不在它的 __dict__ 中?

标签 python

简要上下文:我正在尝试将类的默认参数编辑为其 __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/

相关文章:

python - 了解 Django 的数据库 API 和模型 - Poll.objects

python - 在 pylearn2 中使用 RBM 预训练 ANN

python - 在 Snow Leopard 中安装 VPython?

python - Tensorflow 对象检测 API 训练和导出图

python - 在 pandas 中将字符串转换为数字

python - Matplotlib 半色轴

python - 多处理 Python 中的写入错误

python - Django 文件上传 - fileno 错误

python - 在 Pandas 数据框中插入缺失的类别和日期

python - 从 Gmail 导出邮件