【问题标题】:Understand how slots work with dictionary class了解插槽如何与字典类一起使用
【发布时间】: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

【问题讨论】:

标签: python python-3.x slots


【解决方案1】:

解压您提供的关键字参数:

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

并遍历kwargs.items() 以获取键值对。

在您正在执行的通话中:

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

您提供的字典被分配给iterable 而不是kwargs,因为您将它作为位置传递。 **kwargs 在这种情况下为空,不执行任何分配。

请记住,**kwargs 获取多余的关键字参数,而不仅仅是传递的任何字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2012-05-20
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多