【发布时间】:2018-01-01 13:47:06
【问题描述】:
最近有人向我指出__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
【问题讨论】:
-
1.当您传递字典对象时,
kwargs为空。 2. 如果需要字典的键值对,遍历dict.items。
标签: python python-3.x slots