__new__ 方法负责创建一个实例对象,__init__ 方法负责将该实例对象进行初始化
class Myclass(object):
def __init__(self, x):print self.x
class Foo(object):
def __init__(self, *args, **kwargs):
print 'foo'
def __new__(cls, *args, **kwargs):
return object.__new__(Stranger, *args, **kwargs)
def func(self):
print 'func called'
class Stranger(object):
def __new__(cls, *args, **kwargs):
print 'Stranger __new__ called'
def __init__(self,*args,**kwargs):
print 'stranger'
self.name='name'
def display(self):
print self.name
foo = Foo()
foo.__init__(foo)
foo.func()
输出:
stranger
AttributeError: 'Stranger' object has no attribute 'func'