Python的插槽是否包含方法?

时间:2015-06-18 10:30:11

标签: python slots

让我说我做这个课:

class Person:
   __slots__ = ["j"]

   def __init__(self):
       self.j = 1

   def hello(self):
       print("Hello")

插槽中的方法是 hello 吗?

1 个答案:

答案 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'>