了解插槽如何与字典一起使用 class

Understand how slots work with dictionary class

最近有人向我指出了 __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)

虽然第一个 class 按预期工作,但第二个 class 会给我一个属性错误。 __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 抓取 多余的关键字参数 而不仅仅是传递的任何字典。