简体   繁体   中英

Use of __slots__ in an agent-based model written in Python

I am interested in building agent-based models of economic systems in Python. Typical model might have many thousands of agents (ie, firms, consumers, etc).

Typical firm agent class might look something like:

class Firm(object):

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

In most of my models, attributes are not dynamically created and thus I could write the class using __slots__ :

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

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

However, it seems that the use of __slots__ is generally discouraged. I am wondering if this be a legitimate/advisable use case for __slots__ .

The __slots__ feature is specifically meant to save memory when creating a large number of instances. Quoting the __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.

Sounds like you are using slots for exactly the right reasons .

What is discouraged is to use __slots__ for the no-dynamic-attributes side effect; you should use a metaclass for that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM