python 中的__new__与__init__

在Python中的class中有两个方法__new__与__init__,有什么区别呢?

class TestCls():

"""docstring for TestCls"""

  def __init__(self, name):

    print('init')

    print(self)

    print(type(self)) self.name = name

   def __new__(cls, name):

    print('new')

    print(cls)

    print(type(cls))

    return super().__new__(cls)

c = TestCls("CooMark")

# new...

# <class '__main__.TestCls'>

# <class 'type'> # init...

 

 

# <__main__.TestCls object at 0x02201130>

# <class '__main__.TestCls'>

 

异同点:

  1. 参数
    • __new__的第一个占位参数是class对象
    • __init__的第一个占位参数是class的实例对象
    • 其他的参数应一致
  2. 作用
    • __new__ 用来创建实例,在返回的实例上执行__init__,如果不返回实例那么__init__将不会执行
    • __init__ 用来初始化实例,设置属性什么的

posted on 2018-03-22 16:22  辰辰宝贝  阅读(203)  评论(0编辑  收藏  举报