【转载】python: __init__ 和 __new__的区别

【转】python中的__init__和__new__的区别

编程语言博大精深,能弄懂一点是一点吧

一言蔽之就是:

  • new 为类级别语句(创建类的时候执行)
  • init 为实例级别语句(创建对象-即实例化的时候执行)

不同的表现:

  • __ init__
class PositiveInteger(int):

    def __init__(self, value):
        self.value = abs(value)


if __name__ == "__main__":

    i = PositiveInteger(-2)
    print(i)  # -2
  • __ new__
class PositiveInteger(int):

    def __new__(cls, value):
        return abs(value)


if __name__ == "__main__":

    i = PositiveInteger(-2)
    print(i)  # 2

它这是让PositiveInteger继承了int类,想创建一个int的时候执行某些操作,
但在__init__里面没生效,只能到__new__才生效…

猜你喜欢

转载自blog.csdn.net/chen_holy/article/details/89764931