self组成的类中的self变量列表

self组成的类中的self变量列表

本文介绍了Python-如何获取由N-self组成的类中的self变量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成N个座席.每个代理都有一个名称,因此我会从名称中创建一个随机名称,并将其分配给Agent类.

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.

这是来自"mesa"的信息:

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()

在互动环节

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

我收到此错误:

文件"C:\ src__init __.py",第7行,在 atr = list([MoneyAgent.name中的a表示])AttributeError:类型对象'MoneyAgent'没有属性'name'

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

如何解决?

推荐答案

以下是我对您的问题的解释:您正在创建一个MoneyModel对象,其中包含MoneyAgent个对象的集合,这些对象存储在引用的类似集合的对象中表示为MoneyModel.schedule,并且您想要MoneyModel.schedule集合中每个MoneyAgent对象的namelist.

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.

假设MoneyModel.schedule表现为可迭代对象,则以下内容应起作用:

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

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

这篇关于Python-如何获取由N-self组成的类中的self变量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:15