简体   繁体   English

我如何在子类中验证 __slots__?

[英]How can I validate __slots__ in child classes?

From the python docs 3.3.2.4.1 , it says " __slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots)."python 文档 3.3.2.4.1中,它说“在父类中声明的__slots__在子类中可用。但是,子类将获得__dict____weakref__除非它们还定义了__slots__ (它应该只包含任何附加插槽的名称)。 “

However, while I was testing this as below:但是,当我如下测试时:

class A(object):
    __slots__ = ('a')

class B(A):
    __slots__ = ('b')

b = B()
B.z = 'z'
B.a = 'a'
print(B.z) #z
print(B.a) #a
print(B.__dict__) #{'__module__': '__main__', '__slots__': ('b',), 'b': <member 'b' of 'B' objects>, '__doc__': None, 'z': 'z', 'a': 'a'}

Neither Bz nor B.__dict__ throws exception, the code manages to output. BzB.__dict__都没有抛出异常,代码管理到 output。

I am confused why the __slots__ = ('b') in Class B doesn't validate.我很困惑为什么Class B中的__slots__ = ('b')无法验证。 Theoretically, it should throw an exception at Bz because the keys in slots don't contain it.理论上,它应该在 Bz 处抛出异常,因为槽中的键不包含它。

Could you please help to explain this strange point?你能帮忙解释一下这个奇怪的点吗? And if possible, could you please help to provide the right usage method of slots in child classes?如果可能的话,您能否帮助提供子类中插槽的正确使用方法?

By the way, my python version is 3.9.7对了,我的python版本是3.9.7

Thank you so much.太感谢了。

The __slots__ should be a tuple there, but you don't actually have a tuple, you have a string. __slots__应该是一个元组,但你实际上没有元组,你有一个字符串。 Try doing __slots__ = ("a",) .尝试做__slots__ = ("a",)

Also, the slots apply to instances, not classes.此外,插槽适用于实例,而不适用于类。 You are assigning the attribute to the class object. Try the following.您正在将属性分配给 class object。请尝试以下操作。 The instances work as expected.这些实例按预期工作。

a = A()
a.a = "a"
# a.b = "b"  # fails

b = B()
b.b = "b"
b.a = 'a'
# b.z = 'z'  # fails

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM