python - 在用 Python 编写的基于代理的模型中使用 __slots__

标签 python agent agent-based-modeling

我有兴趣 build agent-based models Python 中的经济系统。典型的模型可能有成千上万的代理人(即公司、消费者等)。

典型的公司代理类可能类似于:

class Firm(object):

    def __init__(capital, labor, productivity):
        self.capital = capital
        self.labor = labor
        self.productivity = productivity

在我的大多数模型中,属性不是动态创建的,因此我可以使用 __slots__ 编写类:

class Firm(object):
    __slots__ = ('capital', 'labor', 'productivity')

    def __init__(capital, labor, productivity):
        self.capital = capital
        self.labor = labor
        self.productivity = productivity

然而,它seems通常不鼓励使用 __slots__。我想知道这是否是 __slots__ 的合法/可取用例。

最佳答案

__slots__ 特性专门用于在创建大量实例时节省内存。引用 __slots__ documenation :

By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

The default can be overridden by defining __slots__ in a new-style class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

听起来您使用插槽的原因完全正确

不鼓励使用 __slots__ 来实现无动态属性的副作用;您应该为此使用元类。

关于python - 在用 Python 编写的基于代理的模型中使用 __slots__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532041/

相关文章:

agent-based-modeling - 基于代理的软件工程问题模拟?

python - 比较python中的两个坐标列表并使用坐标值赋值

python - "Try it Out"部分中的 Django Rest Swagger 自定义身份验证 header

hadoop - Flume 代理 - 我可以指定像 gzip 或 bz2 这样的压缩吗?

artificial-intelligence - 人工智能 - 清洁和油漆的智能代理

javascript - Django Inlineformset - 基于第二个下拉菜单的 JQuery 下拉菜单

python - 用python遍历树的解决方案

azure - 在自托管 Azure DevOps Agent 上安装 ChromeDriver

social-networking - NetLogo:比较邻居的值