python - Understand how slots work with dictionary class -


somebody pointed me usage of __slots__ find on internet improve memory usage

class passenger2():     __slots__ = ['first_name', 'last_name']     def __init__(self, iterable=(), **kwargs):         key, value in kwargs:             setattr(self, key, value)  class passenger():     def __init__(self, iterable=(), **kwargs):         self.__dict__.update(iterable, **kwargs)  # no slots magic works 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 first class works intended, second class give me attribute-error. correct usage of __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 

unpack keyword arguments supply:

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

and iterate through kwargs.items() grab key-value pair.

in call you're performing:

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

the dictionary supply gets assigned iterable , not kwargs because pass positional. **kwargs empty in case , no assigning performed.

remember, **kwargs grabs the excess keyword arguments not dictionary passed.


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -