了解插槽如何与字典类工作
问题描述:
有人最近指出我的__slots__
使用什么我可以在互联网上找到的是,它可以提高内存的使用了解插槽如何与字典类工作
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)
虽然第一类按预期工作,第二类会给我一个属性错误。什么是__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
答
拆开正确使用你提供的关键字参数:
p2 = Passenger2(**{'first_name' : 'abc', 'last_name' : 'def'})
,并通过kwargs.items()
迭代抢键值对。
在呼叫你执行:
p2 = Passenger2({'first_name' : 'abc', 'last_name' : 'def'})
您提供被分配到iterable
,而不是kwargs
,因为你把它作为一个位置的字典。在这种情况下,**kwargs
为空并且不执行分配。
请记住,**kwargs
grafted 多余的关键字参数不只是任何传递的字典。
1.当你传递一个字典对象时,'kwargs'是空的。 2.如果您需要字典的键值对,请遍历“dict.items”。 – vaultah
请参阅此,https://*.com/questions/472000/usage-of-slots –