Ludisposed Ludisposed - 3 years ago 93
Python Question

Understand how slots work with dictionary class

Somebody recently pointed me to the usage of

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'})

p2 = Passenger2({'first_name' : 'abc', 'last_name' : 'def'})

While the First class works as intended, the second class will give me an attribute-error. What is the correct usage of the

Traceback (most recent call last):
File "C:/Users/Educontract/AppData/Local/Programs/Python/Python36-32/", line 10, in <module>
AttributeError: first_name

Answer Source

Unpack the keyword arguments you supply:

p2 = Passenger2(**{'first_name' : 'abc', 'last_name' : 'def'})

and iterate through kwargs.items().

In your form, the dictionary you supply gets assigned to iterable and not kwargs because you pass it as a positional. **kwargs grabs the excess keyword arguments not just any dictionary that is passed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download