让我说我做这个课:
class Person:
__slots__ = ["j"]
def __init__(self):
self.j = 1
def hello(self):
print("Hello")
插槽中的方法是 hello 吗?
答案 0 :(得分:1)
您是否使用__slots__
来控制实例属性,方法存储在类中,而不是实例:
>>> class Slots:
__slots__ = ['attr']
def __init__(self):
self.attr = None
def method(self):
pass
>>> class NoSlots:
def __init__(self):
self.attr = None
def method(self):
pass
>>> 'method' in Slots.__dict__
True
>>> 'method' in NoSlots.__dict__
True
>>> 'method' in NoSlots().__dict__
False
使用__slots__
实际上会生成所有已定义的属性descriptors(另请参阅the how-to),这些属性也存储在类中:
>>> 'attr' in Slots.__dict__
True
>>> type(Slots.attr)
<class 'member_descriptor'>