What's relationship between dict and attrs in python?
我是Python的初学者。我正在学习元类,但我不太明白字典是如何存储方法和属性的?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name=='Model': return type.__new__(cls, name, bases, attrs) print('Found model: %s' % name) mappings = dict() for k, v in attrs.items(): if isinstance(v, Field): print('Found mapping: %s ==> %s' % (k, v)) mappings[k] = v for k in mappings.keys(): attrs.pop(k) attrs['__mappings__'] = mappings attrs['__table__'] = name return type.__new__(cls, name, bases, attrs) |
我假设ATTR不仅可以存储变量,还可以存储方法。如果是这样的话,那么字典里的键和值是什么,attrs?
类的所有属性实际上都存储在字典中。注意,方法也只是属性;它们恰好是可调用的。Python在很多地方使用字典;例如,模块的全局命名空间也是字典。它通常是
类语句的主体像函数一样执行,然后将生成的本地命名空间(通过调用
见
The class’s suite is then executed in a new execution frame (see [Naming and binding](The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.
大胆强调我的。
您可以在数据模型文档的元类部分中找到更多详细信息;引用创建类对象部分:
Once the class namespace has been populated by executing the class body, the class object is created by calling
metaclass(name, bases, namespace, **kwds)
然后,通过
数据模型文档也包含在自定义类部分中:
A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g.,
C.x is translated toC.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes).
您可能还需要读取描述符;方法是通过将类命名空间中的函数绑定到查找方法名的实例来创建的。