Do Python's slots contain methods?

570 views Asked by At

Let's say I do this class:

class Person:
   __slots__ = ["j"]

   def __init__(self):
       self.j = 1

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

Is the method hello in the slots?

1

There are 1 answers

0
jonrsharpe On

Whether or not you're using __slots__ to control instance attributes, methods are stored on the class, not the instance:

>>> 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

Using __slots__ actually makes all defined attributes descriptors (see also the how-to), which are also stored on the class:

>>> 'attr' in Slots.__dict__
True
>>> type(Slots.attr)
<class 'member_descriptor'>