Python- how to get list of self variables in a class consist of N-self

允我心安 提交于 2019-12-02 22:37:32

问题


Edited:

I want to generate N-number of agents. Each agent will have a name, so I create a random name from names and assigned it to class Agent.

After I run the model, I want to get the list of my agents name.

This is from mesa:

import names
from mesa import Agent, Model
from mesa.time import RandomActivation

class Agent(Agent):
    def __init__(self, name):
        self.name= names.get_full_name()
        self.wealth = 1

    def step(self):
        pass

class Model(Model):
    def __init__(self, N):
        self.num_agents = N
        self.schedule = RandomActivation(self)

        for i in range(N):
            a = MoneyAgent(i)
            self.schedule.add(a)

    def step(self):
        self.schedule.step()

on interactive session

gow = MoneyModel(10)
gow.step()
atr = list([a for a in MoneyAgent.name])
print(atr)

I got this error:

File "C:\src__init__.py", line 7, in atr = list([a for a in MoneyAgent.name]) AttributeError: type object 'MoneyAgent' has no attribute 'name'

How to fix it?


回答1:


Here's my interpretation of your problem: You're creating a MoneyModel object which contains a collection of MoneyAgent objects stored in a collection-like object referred to as MoneyModel.schedule, and you want a list of the names of each MoneyAgent object within your MoneyModel.schedule collection.

Assuming MoneyModel.schedule behaves as an iterable object, the following should work:

atr = [agent.name for agent in gow.schedule]


来源:https://stackoverflow.com/questions/41101440/python-how-to-get-list-of-self-variables-in-a-class-consist-of-n-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!