码迷,mamicode.com
首页 > 其他好文 > 详细

__init__ __new__区别

时间:2014-12-01 18:53:17      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   sp   on   div   问题   

请运行代码:

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的类型。

 

__init__ __new__区别

标签:style   blog   http   color   使用   sp   on   div   问题   

原文地址:http://www.cnblogs.com/tom-zhao/p/4135522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!