在下面的示例中,我尝试创建一个Python元类,用
__slots__
和默认值初始化我的类。class Meta(type):
def __new__(cls, name, bases, dictionary, defaults):
dictionary['__slots__'] = list(defaults.keys())
obj = super().__new__(cls, name, bases, dictionary)
return obj
def __init__(self, name, bases, dictionary, defaults):
for s in defaults:
setattr(self, s, defaults[s])
class A(metaclass = Meta, defaults = {'a':123, 'b':987}):
pass
实例化类 A
,我得到了以下结果:
a = A()
>>> dir (a)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'a', 'b']
-> OK
>>> a.c = 500
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
a.c = 500
AttributeError: 'A' object has no attribute 'c'
-> OK
>>> a.b = 40
Traceback (most recent call last):
File "<pyshell#88>", line 1, in <module>
a.b = 40
AttributeError: 'A' object attribute 'b' is read-only
-> 不行,期望a.b
是可读写的
正如您所看到的,元类Meta
正确创建了__slots__
并正确设置了默认值,但不幸的是,由于某些我不理解的原因,这些属性被设置为只读。
是否可能从元类Meta
获取具有读/写功能的slotted属性?