请运行代码:

class A:
    def __init__(self):
        print "A.__init"

    def __new__(self):
        print "A.__new"


class B(object):
    def __init__(self):
        print "B.__init"
        super(B, self).__init__()

    def __new__(cls):
        print "B.__new__"
        return super(B,cls).__new__(cls)


a = A()
b = B()
print(type(a))
print(type(b))

运行结果

A.__init
B.__new__
B.__init
<type 'instance'>
<class '__main__.B'>

请注意:  A无基类,B有基类并且__new__ 方法跟__init__两个方法有两点不同

1.self,cls参数不同,即 __new__为classmethod.

2.__new__有return。

这两个问题牵涉到概念New-style and classic classes。请参照https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes查看classic和new style clas,两者是如何出现的。

不管是new style或者classic都可以使用isinstance(obj, cls)做判断。

因为a虽然现实type 'instance'。但是查看a.__class__仍然可以看到a的类型。

 

posted on 2014-12-01 17:12  tom_zhao_vip  阅读(159)  评论(0编辑  收藏  举报