【问题标题】:Python error "__init__() takes 1 positional argument but 2 were given"Python 错误“__init__() 采用 1 个位置参数,但给出了 2 个”
【发布时间】:2017-07-11 11:34:28
【问题描述】:

Python新手,只是写了一个点头示例,得到一个奇怪的错误。

显示.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 个参数?

【问题讨论】:

  • 一个类似的问题和很好的解释在这里stackoverflow.com/questions/23944657
  • 天啊!发现 C++ 程序员尝试使用 python。那个该死的自己每次都会抓住我。
  • 尝试将 self 作为第一个参数添加到方法中。

标签: python python-3.x


【解决方案1】:

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

根据您定义 GraphicsDisplay init 的方式,这是正确的方法:

display = GraphicsDisplay(win)

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

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

【讨论】:

    【解决方案2】:

    那行应该是这样的:

    super(GraphicsDisplay, self).__init__()
    

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

    问题也可能与类覆盖有关

    【讨论】:

    • 在 python 3 中发生了变化。 super().__init__() 是正确的方法。
    猜你喜欢
    • 2019-01-06
    • 2022-10-06
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多