繁体   English   中英

Python-子类TypeError:最多接受2个参数(给定3个),而应该接受3个

[英]Python - Subclass TypeError: takes at most 2 arguments (3 given) while it should take 3

我正在从父类编写子类,如下所示:

在ParentClass.py中:

class ParentClass(Object):
    def __init__(self, reg, wr=None, rd=None):
        self.register = reg
        self.wr=wr
        self.rd=rd

    def other_function(self):
        ...

在ChildClass.py中:

import ParentClass

class ChildClass(ParentClass):
    def __init__(self, reg, wr, rd):
        super().__init__(reg, wr, rd)    

    def other_function(self):
        override parent class...

我的主要目的是在此处覆盖other_function。 但是,运行代码时出现以下错误:

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

该错误对我来说没有任何意义,因为我已经传递了3个参数,并且父类也接受了3个参数。 2来自哪里? 我的代码有什么问题吗?

谢谢

问题在于ParentClass指错了东西。 import ParentClassParentClass是一个模块 ,而不是一个

import ParentClass

print(ParentClass)
# output: <module 'ParentClass' from 'C:\foo\ParentClass.py'>

您可以将ParentClass类直接导入您的名称空间:

from ParentClass import ParentClass

# now it's as expected:
print(ParentClass)
# output: <class ParentClass.ParentClass>

或保持导入不变,并通过导入的模块访问该类:

import ParentClass

class ChildClass(ParentClass.ParentClass):
    ...

在ChildClass.py中,我应该这样做

from ParentClass import ParentClass

那将正确导入ParentClass而不是其模块

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM