调用元类基时出错:function() 参数 1 必须是 code,而不是 str
我今天早些时候尝试对 threading.Condition 进行子类化,但没有成功。这是当我尝试子类化 threading.Condition 类时 Python 解释器的输出:
>>> import threading
>>> class ThisWontWork(threading.Condition):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
有人可以解释这个错误吗?谢谢!
I tried to subclass threading.Condition earlier today but it didn't work out. Here is the output of the Python interpreter when I try to subclass the threading.Condition class:
>>> import threading
>>> class ThisWontWork(threading.Condition):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
Can someone explain this error? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您会收到该异常,因为尽管它的名称类似于类,但
threading.Condition
是一个函数,并且您不能对函数进行子类化。这个不太有用的错误消息已在 Python bugtracker 上提出,但已被标记为“won不修。”
You're getting that exception because, despite its class-like name,
threading.Condition
is a function, and you cannot subclass functions.This not-very-helpful error message has been raised on the Python bugtracker, but it has been marked "won't fix."
与 OP 遇到的问题不同,但如果您尝试从模块而不是类进行子类化(例如,您尝试继承 My.Module 而不是 My.Module.Class),您也可能会收到此错误。感谢这篇文章帮助我解决了这个问题。
Different problem than OP had, but you can also get this error if you try to subclass from a module instead of a class (e.g. you try to inherit My.Module instead of My.Module.Class). Kudos to this post for helping me figure this out.
关于子类化模块,如果您在文件 Foo.py 中定义了类 Foo,那么这是一个非常容易犯的错误。
当您在不同的文件中创建 Foo 的子类时,您可能会意外地执行以下操作(这是对模块进行子类化的尝试,并将导致错误):
当您确实需要执行以下任一操作时:
或:
With respect to subclassing a module, this is a really easy mistake to make if you have, for example, class Foo defined in a file Foo.py.
When you create a subclass of Foo in a different file, you might accidentally do the following (this is an attempt to subclass a module and will result in an error):
when you really need to do either:
or:
遇到了同样的问题。最终通过仔细查看代码解决了这个问题,这就是关于字符串而不是代码发出警报的
TypeError
出现的地方。“并且”
请注意,由于单个小写字母而出现特定错误到代码“Model”,这又使其成为一个字符串
Gotten into the same problem. Finally solved by taking a keen look at the code and this is where the
TypeError
that alarms about a string instead of code comes about.."And"
Notice that specific error comes about because of a single lowercase letter to the code "Model" which in turn makes it a string