Python错误" __ init __()需要1个位置参数但是2个被给出"

时间:2017-07-11 11:34:28

标签: python python-3.x

Python新手,只是编写一个例子,得到一个奇怪的错误。

display.py

import abc
from graphics import *

class Display:
    pass

class Visual(metaclass=abc.ABCMeta):
    """Represents a thing which can be drawn on a display"""

    @abc.abstractmethod
    def draw(disp: Display) -> None:
        """Draws the visual to the display"""
        raise NotImplementedError()


class Display(metaclass=abc.ABCMeta):
    def __init__(self) -> None:
        __visuals = []

    def add_visual( vis: Visual ):
        __visuals.append(vis)

    def draw() -> None:
        for visual in __visuals:
            visual.draw(self)

graphics_display.py

from graphics import *
from gfx.display import Display

class GraphicsDisplay(Display):
    def __init__(self, window : GraphWin) -> None:
        super().__init__()
        __window = window

    def get_window() -> GraphWin:
        return __window

追溯是

>>> win = GraphWin()
>>> display = GraphicsDisplay(window=win)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/julian/test/gfx_test/gfx/graphics_display.py", line 6, in __init__
    Display.__init__(self)
TypeError: __init__() takes 1 positional argument but 2 were given

graphics.py就在这里

为什么认为基础 init 获得2个参数?

2 个答案:

答案 0 :(得分:0)

该行应如下所示:

super(GraphicsDisplay, self).__init__()

当您在没有参数的情况下调用super()时,您将获得非绑定的父类实例,因此方法__init__()不会获得self个对象作为第一个论点传递。

问题也可能出在班级重写

答案 1 :(得分:0)

您已将参数窗口定义为位置参数,但随后使用关键字参数对其进行了初始化。

这是基于您如何定义 GraphicsDisplay init 的正确方法:

df <- data.frame(
  id = 1:13,
  type = c("A","B","A","A","B","A","B","A","B","A","A","A","B")
)

或者,将您的 init 定义更改为具有默认值的关键字参数:

display = GraphicsDisplay(win)