[Python] 新式类中 __new__的理解

__new__ 方法负责创建一个实例对象,__init__ 方法负责将该实例对象进行初始化


class Myclass(object):

    def __init__(self, x):
        self.x = x



self= Myclass.__new__(Myclass)
Myclass.__init__(self, 10)

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'


你可能感兴趣的:(python)