Slots in python inheritance
本问题已经有最佳答案,请猛点这里访问。
我理解,一旦我们添加了
但我不完全理解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Vector(object): __slots__ = ('name','age') def __init__(self): self.name = None self.age = None class VectorSub(Vector): def __init__(self): self.name = None self.age = None self.c = None a = Vector() # b = VectorSub() print dir(a) # __slots__ defined and no __dict__ defined here, understandable print dir(b) # Both __dict__ and __slot__ defined. #So __slots__ is inherited for sure. print a.__dict__ #AttributeError: has no attribute '__dict__, understandable print b.__dict__ #{'c': None} ... How? print b.name # Works, but why? 'name' not in b,__dict__ |
这就是我困惑的时候。首先,如果继承了
摘自python的
The action of a slots declaration is limited to the class where it is defined. As a result, subclasses will have a dict unless they also define slots (which must only contain names of any additional slots).
因此,
还有几条值得一提的注释,请检查插槽文档