Я переопределяю метод __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 >
myinit called, args = (), kwargs = {}
Кажется, единственный способ заставить myinit()
работать — это явно вызвать его как self.__init__()
внутри myclass.__init__()
.