我目前正在实施开槽元类使用type()
:Python的__slots__元类问题
type(i,(), {'__slots__': tuple(data)
我当然会非常有槽保持,因为我有一个会从他们的更小的内存占用和提高访问速度受益的用例。
当我这样做:但是当我运行
dir(slotted_class)
>>>['__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__',
'slotted_attribute1',
'slotted_attribute2',
'slotted_attribute3',
'slotted_attribute4']
:
slottedclass.slotted_attribute1
我收到以下错误:
>>> AttributeError Traceback (most recent call last)
<ipython-input-58-88291109fa74> in <module>()
----> 1 slotted_class.slotted_attribute1
AttributeError: slotted_attribute1
编辑:欲了解更多的信息,甚至更多的困惑: 如果我直接实施一个等价物而不使用元类:
class slottedclass_non_meta(object):
__slots__ = ['slotted_attribute1', 'slotted_attribute2', 'slotted_attribute3', 'slotted_attribute4']
def __init__(self, slotted_attribute1, slotted_attribute2, slotted_attribute3, slotted_attribute4):
self.slotted_attribute1, self.slotted_attribute2, self.slotted_attribute3, self.slotted_attribute4 = slotted_attribute1, slotted_attribute2, slotted_attribute3, slotted_attribute4
然后,让这个比较 目录(slottedclass)==目录(slottedclass_non_meta)
>>> True
什么是完整的错误?这看起来被截断了。 – Carcigenicate
你的对象,而不是“slotted_class”做“slottedClass”大写C那么试试这个“slotted_class.slotted_attribute1” –
我道歉,这仅仅是一个占位符,我写了这个问题本身。然而,错误真的很简单。我将增加整个回溯 – SerialDev