python - 为什么可以在函数定义中用a['xxx'] = 'ooo'的方式创建字典?
高洛峰
高洛峰 2017-04-17 17:50:53
0
1
347

在看python教程的时候发现这个元类定义

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

__new__方法里面的这句attrs['add'] = lambda self, value: self.append(value)
为什么直接生成了一个字典?
对于一个元类,它的__new__方法一定是传这四个参数,而不像类的__new__方法可以传cls外任意参数吗

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
刘奇

The attrs parameter of __new()__ is originally a dictionary, so there is no generation. It just adds some new elements to the original dictionary. __new()__attrs参数本来就是一个字典,所以没有生成一说。只是在原有的字典基础上添加一些新的元素而已。

元类不同于一般的类,它所产生的是类对象,而普通的类产生的是实例对象。元类中namebasesattrs分别代表类名基类类属性。实际类的结构也就这三样

class B(A):
    def __init__(self, name):
        self._name = name

这里的__init__self._name都属于attrs。所以不能传任意参数。

在我看来,元类的作用更倾向于过滤,它可以制定规则。在实际使用类的时候,会先检查是否定义了元类,如果没有则会调用原生的元类即type

Metaclass is different from ordinary classes. It produces class objects, while ordinary classes produce instance objects. In the metaclass, name, bases, and attrs represent class name and base class respectively. , Class attribute. The actual class structure is just these three

rrreee

The __init__ and self._name here both belong to attrs. So you cannot pass any parameters.

In my opinion, the role of metaclass is more towards filtering, it can formulate rules. When the class is actually used, it will first check whether the metaclass is defined. If not, the native metaclass, i.e. type, will be called. #🎜🎜# #🎜🎜#You can check out the official documentation#🎜🎜# #🎜🎜#The above is my understanding. There may be deviations. Corrections are welcome and greatly appreciated. #🎜🎜#
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template