-3

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?

  • 3
    Why not try it and see? – jonrsharpe Jun 18 '15 at 10:31
  • I tried it and it seems to work but maybe functions are stored another way. It is strange that you don't have to implicitly put em in the slots list. –  Jun 18 '15 at 10:35
  • 1
    Yes, they're stored on the *class* not the *instance* - they appear in neither `__slots__` nor `__dict__` on an instance. – jonrsharpe Jun 18 '15 at 10:40

1 Answers1

2

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'>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437