我有兴趣 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/