TypeError: module() takes at most 2 arguments (3 given)

1. 错误提示

 2. 代码

class Parent:
    """定义父类"""
    def __init__(self):
        print("调用父类构造函数")

  

import Parent

class Child(Parent):
    """定义子类"""
    def __init__(self):
        print("调用子类构造方法")

child = Child() # 实例化子类

  

 3. 错误原因

此处想要导入类,如上代码所示只是导入了模块,Python的模块名与类名是在两个不同的名字空间中,初学者很容易将其弄混淆。

python 类

用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例

python 模块

模块,在Python可理解为对应于一个文件。

根据上面代码,你想使用 import Parent 导入Parent 类,但 import Parent 只能导入模块,所以错误

4. 解决方法

方法一
使用正确方式导入类, import Parent from Parent (此操作就是导入Parent 模块中的 Parent 类)

方法二
修改 class Child(Parent): 代码为 class Child(Parent.Parent):,目的也是选中模块中的类

5. 正确调用的代码

  方法一

from Parent import Parent

class Child(Parent):
    """定义子类"""
    def __init__(self):
        print("调用子类构造方法")

child = Child() # 实例化子类

  

方法二

  

import Parent

class Child(Parent.Parent):
    """定义子类"""
    def __init__(self):
        print("调用子类构造方法")

child = Child() # 实例化子类

  

转载

Python:彻底理解并解决错误TypeError: module.__init__() takes at most 2 arguments (3 given)_不懂一休-CSDN博客

原文地址:https://www.cnblogs.com/kevin-hou1991/p/14806598.html