You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mesa教程代码报错:第16行及末行提示缺少表达式

问题解决

你的代码存在几处语法和API使用错误,直接导致了"expected expression"报错:

  1. 函数定义语法错误
    第16行def__init__(self, N):中,def和__init__之间缺少空格,Python语法要求关键字def与函数名之间必须有空格,修正为:
def __init__(self, N):
  1. 调度器类名拼写错误
    mesa.time.randomActivation(self)里的类名应为RandomActivation(首字母大写),Mesa的调度器类采用驼峰命名规则,小写的randomActivation是不存在的未定义对象,修正为:
self.schedule = mesa.time.RandomActivation(self)
  1. 多余且冲突的导入语句
    from tkinter import N完全多余,还会和你定义的模型参数N产生命名冲突,直接删除该行即可。

  2. 可选规范修正
    注释里的purposeses多了一个s,改为purposes即可,不影响运行但更符合语法规范。

修正后的完整代码:

import mesa

class MoneyAgent(mesa.Agent):
    """An agent with fixed initial wealth."""

    def __init__(self, unique_id, model):
        super().__init__(unique_id, model)
        self.wealth = 1
    def step(self):
        # The agent's step will go here.
        # for demonstration purposes we will print the agent's unique_id
        print("Hi, I am agent " + str(self.unique_id) + ".")

class MoneyModel(mesa.Model):
    """ A model with some number of agents."""
    def __init__(self, N):
        self.num_agents = N
        self.schedule = mesa.time.RandomActivation(self)
        # Create agents
       
        for i in range(self.num_agents):
            a = MoneyAgent(i, self)
            self.schedule.add(a)

    def step(self):
        """Advance the model by one step."""
        self.schedule.step()

内容的提问来源于stack exchange,提问作者Parakeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 07:27:08