gpt4 book ai didi

Python - 类型(名称、基础、字典)

转载 作者:太空狗 更新时间:2023-10-30 00:29:52 24 4
gpt4 key购买 nike

文档:

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute.

在学习 Python 时,我遇到过将类型用作“类语句的动态形式”,这似乎非常有趣和有用,我希望更好地理解它。有人可以清楚地解释 __name____bases____dict__ 在一个类中的作用,并举例说明 type(name, bases , dict) 有它自己的权利。

最佳答案

定义类时:

class Foo(Base1, Base2):
bar = 'baz'

def spam(self):
return 'ham'

Python 本质上是这样做的:

def spam(self):
return 'ham'
body = {'bar': 'baz', 'spam': spam}

Foo = type('Foo', (Base1, Base2), body)

然后将 Foo 添加到定义 class 语句的命名空间。

class 语句下的 block 被执行,就好像它是一个没有参数的函数,结果局部命名空间(字典)形成类主体;在这种情况下,形成了一个包含 'bar''spam' 键的字典。

您可以通过将名称字符串、基类元组和带有字符串键的字典传递给 type() 函数来获得相同的结果。

一旦你也开始探索元类(它们本质上是 type() 的子类),让您自定义类的创建方式),您会发现 body 并不 是一个普通的字典。 PEP 3115 - Metaclasses in Python 3将可能的值扩展为任何 dict like,让您可以通过为类主体使用扩充字典来实现各种有趣的类行为。新Python 3.4 enum module例如,使用 OrderedDict() instance相反,保留属性顺序。

关于Python - 类型(名称、基础、字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22609272/

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