代码之家  ›  专栏  ›  技术社区  ›  SuperCiocia

Python:init和new的区别[重复]

  •  0
  • SuperCiocia  · 技术社区  · 7 年前

    我试着去理解 __init__ __new__ 在Python2.7的类中

    我有这个示例代码:

    class Point(object):
    
        def __new__(cls,*args,**kwargs):
            print("From new")
            print(cls)
            print(args)
            print(kwargs)
    
            # create our object and return it
            obj = super().__new__(cls)
            return obj
    
        def __init__(self,x = 0,y = 0):
            print("From init")
            self.x = x
            self.y = y
    
    p = Point(2,3)
    

    • It错误

    obj=超级()。 新的 (中央情报局) TypeError:super()至少接受1个参数(给定0)

    • super() ,和 __初始__ 似乎没有运行,因为看不到它的打印语句。

    你知道为什么吗?

    0 回复  |  直到 7 年前