gpt4 book ai didi

python - 为什么 Python 在创建实例时不调用实例方法 __init__() 而是调用类提供的 __init__() ?

转载 作者:太空狗 更新时间:2023-10-29 17:44:16 29 4
gpt4 key购买 nike

我正在覆盖类的 __new__() 方法以返回具有特定 __init__() 集的类实例。 Python 似乎调用类提供的 __init__() 方法而不是特定于实例的方法,尽管 Python 文档在

http://docs.python.org/reference/datamodel.html

说:

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

这是我的测试代码:

#!/usr/bin/env python

import new

def myinit(self, *args, **kwargs):
print "myinit called, args = %s, kwargs = %s" % (args, kwargs)


class myclass(object):
def __new__(cls, *args, **kwargs):
ret = object.__new__(cls)

ret.__init__ = new.instancemethod(myinit, ret, cls)
return ret

def __init__(self, *args, **kwargs):
print "myclass.__init__ called, self.__init__ is %s" % self.__init__
self.__init__(*args, **kwargs)

a = myclass()

哪些输出

$ python --version
Python 2.6.6
$ ./mytest.py
myclass.__init__ called, self.__init__ is <bound method myclass.myinit of <__main__.myclass object at 0x7fa72155c790>>
myinit called, args = (), kwargs = {}

似乎让 myinit() 运行的唯一方法是在 myclass.__init__() 中显式调用它作为 self.__init__()

最佳答案

新式类的特殊方法是根据实例的类型而不是实例本身来查找的。这是 documented behaviour :

For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes):

>>> class C(object):
... pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()

关于python - 为什么 Python 在创建实例时不调用实例方法 __init__() 而是调用类提供的 __init__() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635489/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com