【问题标题】:How to solve python error: TypeError: __init__() takes exactly 4 arguments (5 given)如何解决 python 错误:TypeError: __init__() 正好需要 4 个参数(给定 5 个)
【发布时间】:2022-01-25 18:42:59
【问题描述】:

我是 Python 新手。有人可以帮我解决这个错误吗?

我的代码如下,

class First:
    def passThisArgs(self, a, b, c):
        return Second(self, a, b, c)

class Second:
    def __init__(self, a, b, c):
        print 'Values are :\n', a, b, c

newObj = First()
a = 5
b = 6
c = 7
newObj.passThisArgs(a, b, c)

我收到此错误:

Traceback (most recent call last):
  File "/root/PycharmProjects/abc.py", line 13, in <module>
    newObj.passThisArgs(a, b, c)
  File "/root/PycharmProjects/abc.py", line 3, in passThisArgs
    return Second(self, a, b, c)
TypeError: __init__() takes exactly 4 arguments (5 given)

我在 Linux 中使用 python 2.7。

【问题讨论】:

    标签: python class init


    【解决方案1】:

    您不会将“自我”传递给另一个班级。 Python 将创建一个全新的对象并自动将其作为self 参数传递给__init__。所以:

            return Second(a,b,c)
    

    【讨论】:

    • 好的。谢谢@tim-roberts,这解决了我的错误。我刚刚发现return Second() 中的self 将创建一个新对象并将其传递给First()init
    • 再次感谢。我学到了一个新概念。当我从passThisArgs 捕获self 时,我得到它如下&lt;__main__.First instance at 0x2&gt;。意味着一个类中的每个self 都会创建自己的对象,我们也可以在另一个类中使用来自self 的变量和方法(如果传递了它,因为我第一次错误地传递了它)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多