【问题标题】:i dont understand why my super() is producing an error我不明白为什么我的 super() 会产生错误
【发布时间】:2020-04-20 10:37:42
【问题描述】:

如果我这样编码,为什么我的程序可以工作:

class Shape:

    class Shape:
    shape_type = ""

    def __init__(self, c='*'):
        self.color = c

class Square(Shape):
    shape_type = "Quadrat"

    def __init__(self, w, *args, **kwargs):
        Shape.__init__(self, *args, **kwargs)
        self._width = w

q1 = Square(4, c="#")

但如果我使用 super() 函数则不会

class Shape:
    shape_type = ""

    def __init__(self, c='*'):
        self.color = c

class Square(Shape):
    shape_type = "Quadrat"

    def __init__(self, w, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        self._width = w

q1 = Square(4, c="#")

它说 TypeError: init() got multiple values for argument 'c'.

【问题讨论】:

    标签: python class object arguments super


    【解决方案1】:

    删除self

    class Shape:
        shape_type = ""
    
        def __init__(self, c='*'):
            self.color = c
    
    class Square(Shape):
        shape_type = "Quadrat"
    
        def __init__(self, w, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self._width = w
    
    q1 = Square(4, c="#")
    

    使用super() 时,您不必提供self 参数,因为您是在实例而不是类上执行__init__

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多