Somebody recently pointed me to the usage of __slots__
What I could find on the internet is that it could improve memory usage
class Passenger2():
__slots__ = ['first_name', 'last_name']
def __init__(self, iterable=(), **kwargs):
for key, value in kwargs:
setattr(self, key, value)
class Passenger():
def __init__(self, iterable=(), **kwargs):
self.__dict__.update(iterable, **kwargs)
# NO SLOTS MAGIC works as intended
p = Passenger({'first_name' : 'abc', 'last_name' : 'def'})
print(p.first_name)
print(p.last_name)
# SLOTS MAGIC
p2 = Passenger2({'first_name' : 'abc', 'last_name' : 'def'})
print(p2.first_name)
print(p2.last_name)
While the First class works as intended, the second class will give me an attribute-error. What is the correct usage of the __slots__
Traceback (most recent call last):
File "C:/Users/Educontract/AppData/Local/Programs/Python/Python36-32/tester.py", line 10, in <module>
print(p.first_name)
AttributeError: first_name