An object with slots has a predefined number and names of members while «ordinary» objects with a __dict__
can be assigned an aribtrary number of objects to any member name.
Demonstration
The following simple demonstration creates two classes, one with slots and one with __dict__
.
After creating one
object for each
class, the members of each class are stored in a
set (
members_s
and
members_d
) and the
set
operator -
is used to find which members exist in one class but not in the other.
It turns out that the slot-object has
__slots__
(as expected), is missing
__dict__
(also expected) but is also missing
__weakref__
(possibly not expeced).
class MembersInDict:
def __init__(self):
self.num = 42
self.txt = 'Hello world'
# --
class MembersInSlots:
__slots__ = 'num', 'txt'
def __init__(self):
self.num = 42
self.txt = 'Hello world'
d = MembersInDict()
s = MembersInSlots()
members_d = set(dir(d))
members_s = set(dir(s))
print(members_d - members_s)
#
# {'__weakref__', '__dict__'}
print(members_s - members_d)
#
# {'__slots__'}
d.dyn = 'dynamic member'
#
# Following line would throw
# AttributeError: 'MembersInSlots' object has no attribute 'dynamic'
# if not commented.
#
# s.dynamic = 'xyz'
for k, v in d.__dict__.items():
print(f'{k} = {v}')