![](/img/trans.png)
[英]error when calling the metaclass bases function() argument 1 must be code not str
[英]Error when calling the metaclass bases: function() argument 1 must be code, not 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
有人可以解释这个错误吗? 谢谢!
您会收到该异常,因为尽管它的名称类似于类,但threading.Condition
是一个函数,并且您不能对函数进行子类化。
>>> type(threading.Condition)
<type 'function'>
这个不是很有帮助的错误消息已经在 Python bugtracker 上提出,但它被标记为“不会修复”。
与 OP 的问题不同,但如果您尝试从模块而不是类进行子类化(例如,您尝试继承 My.Module 而不是 My.Module.Class),您也会收到此错误。 感谢 这篇文章帮助我解决了这个问题。
TypeError:调用元类基类时出错
对于这个问题,答案是您可能将 Python 类命名为与其所在的模块(即文件)相同的名称。然后您导入了该模块并尝试像使用类一样使用它。 你这样做是因为你和我一样,不久前可能还是一名 Java 程序员:-)。 修复它的方法是导入 module.class 而不仅仅是模块。 或者,为了理智起见,更改类或模块的名称,以便更清楚地了解要导入的内容。
关于对模块进行子类化,例如,如果您在文件 Foo.py 中定义了类 Foo,则这是一个非常容易犯的错误。
当您在不同的文件中创建 Foo 的子类时,您可能会不小心执行以下操作(这是对模块进行子类化的尝试,将导致错误):
import Foo
class SubclassOfFoo(Foo):
当您确实需要执行以下任一操作时:
from Foo import Foo
class SubclassOfFoo(Foo):
或者:
import Foo
class SubclassofFoo(Foo.Foo):
陷入了同样的问题。 最后通过仔细查看代码解决了,这就是TypeError
警告字符串而不是代码的地方。
Class Class_name(models.model): //(gives a TypeError of 'str' type)
“和”
Class Class_name(models.Model): // is the correct one.
请注意,特定错误是由于代码“ Model ”的单个小写字母而导致的,这反过来又使它成为一个字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.