[英]Unexpected keyword argument when using **kwargs in constructor
I'm baffled. 我很困惑。 I'm trying to make a subclass that doesn't care about any keyword parameters -- just passes them all along as is to the superclass, and explicitly sets the one parameter that is required for the constructor.
我正在尝试创建一个不关心任何关键字参数的子类,仅将它们直接传递给超类,并显式设置构造函数所需的一个参数。 Here's a simplified version of my code:
这是我的代码的简化版本:
class BaseClass(object):
def __init__(self, required, optional=None):
pass
def SubClass(BaseClass):
def __init__(self, **kwargs):
super(SubClass, self).__init__(None, **kwargs)
a = SubClass(optional='foo') # this throws TypeError!?!??
This fails with 这失败了
leo@loki$ python minimal.py
Traceback (most recent call last):
File "minimal.py", line 9, in <module>
a = SubClass(optional='foo')
TypeError: SubClass() got an unexpected keyword argument 'optional'
How can it complain about an unexpected keyword argument when the method has **kwargs
? 当方法具有
**kwargs
时,如何抱怨一个意外的关键字参数?
(Python 2.7.3 on Ubuntu) (Ubuntu上的Python 2.7.3)
def SubClass(BaseClass):
is a function, not a class. 是一个函数,而不是一个类。 There's no error because
BaseClass
could be an argument name, and nested functions are allowed. 没有错误,因为
BaseClass
可以是参数名称,并且允许嵌套函数。 Syntax is fun, isn't it? 语法很有趣,不是吗?
class SubClass(BaseClass):
Stumbled on to this post when searching for an answer to the exact same error, but different cause. 在寻找完全相同的错误,但原因不同的答案时,偶然发现了该帖子。
I worked out my problem (python beginners mistake), but thought I should put it up here in case it helps someone else. 我解决了我的问题(python初学者的错误),但是我认为我应该把它放在这里,以防它对其他人有帮助。
My project structure: 我的项目结构:
project\
--package1\
----Module1.py
----Module2.py
--package2\
...blah blah blah...
where Module2 extends Module1, and class names were the same as the module/file names 其中Module2扩展了Module1,并且类名与模块/文件名相同
In Module2.py, I had: 在Module2.py中,我有:
from package1 import Module1
assuming that this would import the classes within. 假设这将在其中导入类。
Received an unexpected keyword argument error when I tried to create Module2 Class 当我尝试创建Module2类时收到意外的关键字参数错误
Mod2 = Module2(kw1=var1, kw2=var2)
Fixed by using 通过使用固定
from package1.Module1 import Module1
That is [package name].[module name] import [class name]
即
[package name].[module name] import [class name]
Hope this helps someone else out there 希望这可以帮助别人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.