在看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
外任意参数吗
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
参数本来就是一个字典,所以没有生成一说。只是在原有的字典基础上添加一些新的元素而已。元类不同于一般的类,它所产生的是类对象,而普通的类产生的是实例对象。元类中
name
,bases
,attrs
分别代表类名
,基类
,类属性
。实际类的结构也就这三样这里的
__init__
和self._name
都属于attrs
。所以不能传任意参数。在我看来,元类的作用更倾向于过滤,它可以制定规则。在实际使用类的时候,会先检查是否定义了元类,如果没有则会调用原生的元类即
Metaclass is different from ordinary classes. It produces class objects, while ordinary classes produce instance objects. In the metaclass,type
name
,bases
, andattrs
representclass name
andbase class
respectively. ,Class attribute
. The actual class structure is just these threerrreee
The__init__
andself._name
here both belong toattrs
. So you cannot pass any parameters.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. #🎜🎜#