python - 从对象子类化是否与将类型定义为元类相同?

标签 python python-2.7 python-internals new-style-class

这是一个老式的类:

class OldStyle:
    pass

这是一个新式类:

class NewStyle(object):
    pass

这也是一个新式类:

class NewStyle2:
    __metaclass__ = type

NewStyleNewStyle2 有什么区别吗?

我的印象是从 object 继承的唯一效果实际上是定义 type 元类,但我找不到任何证实,除此之外我看不出有什么区别。

最佳答案

几乎是的,NewStyleNewStyle2 之间没有区别。两者都是 type 类型,而 OldStyleclassobj 类型。

如果您从对象继承,__class__ of object (meaning type) is going要使用的;如果您提供 __metaclass__ that is going to get picked up .

如果没有作为__metaclass__ 提供并且您没有从object 继承,Py_ClassType is assigned as the metaclass给你。

在所有情况下,metaclass.__new__ 都会被调用。对于 Py_ClassType.__new__ 它遵循定义的语义(我从来没有检查过它们,真的)和对于 type.__new__ it makes sure to pack object在你类(class)的基础上。

当然,类似的效果是通过:

cls = type("NewStyle3", (), {})

立即调用type;这只是一个更大的麻烦:-)

关于python - 从对象子类化是否与将类型定义为元类相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501774/

相关文章:

python - 为什么 __add__ 没有在 Python 的双端队列中实现?

python - CPython:为什么 3 行脚本在解释器中需要远超过 3 个周期才能执行?

python - 如何在scrapy蜘蛛中添加try异常?

python - 如何将命令行参数传递给 ipython

python - 循环数据帧的更快方法?

python - 为什么内部填充仅应用于右侧?

python - Python 何时识别/不识别 main 中的变量?

python - twisted 和 cyclone 的新手 - 如何让 redis 回调为简单的 get 请求工作

python - 如何仅将嵌套列表的某些字符串转换为整数?

python - 使用 ElementTree 获取 XML 元素时遇到问题