gpt4 book ai didi

python - 在 python 中使用类型类创建类型类

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:01 24 4
gpt4 key购买 nike

我正在阅读这篇关于元类的有趣文章 What is a metaclass in Python? .接受的答案显示了如何使用具有以下签名的类型创建类。

type(name of the class, tuple of the parent class (for inheritance, can be empty), dictionary containing attributes names and values)

我尝试使用上述签名创建“类型”类,令我惊讶的是我一开始就被允许创建一个!感谢您的意见!

type = type('type',(),{});

其次,在我使用上面的语法创建了一个类型类之后,我无法做到

myclass = type('myclass',(),{}); 

type = type('type',(),{});

我得到一个错误提示

Traceback (most recent call last): File "", line 1, in TypeError: object.new() takes no parameters

但是,当我尝试以下操作时,我可以成功。

class myclass(object):
pass

我很困惑,因为根据我的理解,上面的代码片段应该调用 type 来尝试创建类“myclass”。发生什么了!?我是否遗漏了一些细节?

最佳答案

你已经用 type = type('type',(),{}) 类型隐藏了类型

请注意,分号在 Python 中是多余的。

所以你正在创建一个不能做任何事情的类型。

这就是后面的 type 中断的原因。

关于python - 在 python 中使用类型类创建类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11197221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com