迭代 __slots__ 并动态分配值的任何方式?

any way of iterating over __slots__ and dynamically assign values?

我正在为基于代理的模型制作一个框架,我有一个 class 称为代理。由于模拟中将有数千个代理,我想使用 __ slots__,它将替换默认的 __ dict__ 并减少内存消耗。我有我的代码结构,以便它从数据 table 中获取代理的参数,我想将存储在 table 中的值分配给具有 table 的 [=25] 的属性=] 名字.

如果下面是数据table,

|  agent_name  |  location  |    attr1    |    attr2   |
|--------------|------------|-------------|------------|
|  agent smith |    NY      |  some value | some value |
|  Neo         |    NY      |  some value | some value |
| Morpheus     |    Zion    |  some value | some value |

然后,如果我创建 3 个代理,我希望它们都具有 .agent_name、.location、.attr1 和 .attr2 属性。

# illustration of what I want
header_of_table = ["agent_name", "location", "attr1", "attr2"]

class agent:
    __slots__ = header_of_table
    def __init__(self, values_in_row):
        # what I ideally want, I know this syntax doesnt work, but this is to get the idea across
        for slotted_attribute, value in zip(self.__slots__, values_in_row):
            self.slotted_attribute = value

我知道您可以在 for 循环中使用 .eval 方法,但我觉得不够干净,我觉得必须有更好的方法。我想知道是否有一种方法可以遍历插槽并为每个属性分配值。

一些提示:

  • 使用__slots__时需要继承object. Python 2
  • A class 应始终大写。
  • 您可以使用 setattr 正如迈克尔在评论中所写。
  • 它叫做 __slots__ 而不是 __slot__

这是一个基于您的代码的工作示例:

# illustration of what I want
header_of_table = ["agent_name", "location", "attr1", "attr2"]

class Agent:
    __slots__ = header_of_table
    def __init__(self, values_in_row):
        for i, slot in enumerate(self.__slots__):
            self.__setattr__(slot, values_in_row[i])

agent = Agent(["foo", "bar", "yellow", "green"])
print(agent.agent_name, agent.location, agent.attr1, agent.attr2)

>>> foo bar yellow green

编辑评论: 如果我理解正确,那么我会做这样的事情来避免污染全局范围。

slotheaders.py:

class SlotHeaders:
    __slots__ = ["agent_name", "location", "attr1", "attr2"]

agent.py:

from slotheaders import SlotHeaders

class Agent(SlotHeaders):
    def __init__(self, values_in_row):
        for i, slot in enumerate(self.__slots__):
            self.__setattr__(slot, values_in_row[i])

agent = Agent(["foo", "bar", "yellow", "green"])
print(agent.agent_name, agent.location, agent.attr1, agent.attr2)