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

Python AttributeError求助:调用queue类buffer属性时提示无此属性

Fixing the AttributeError When Accessing simpy Container in Your queue Class

Hey there! Let's break down why you're hitting that AttributeError: type object 'queue' has no attribute 'buffer' error, and how to fix it quickly.

The Root Cause

Your buffer attribute is defined inside the __init__ method of the queue class—this makes it an instance attribute, not a class attribute. That means it only exists on actual objects (instances) created from the queue class, not on the class itself. When you try to call queue.buffer.put(size), you're trying to access the attribute directly from the class, which doesn't exist there.

How to Fix It

You need to:

  1. Create an instance of your queue class first
  2. Pass that instance (not just individual attributes like port) to your Packet function, then access buffer through the instance

Here's the corrected code with clear explanations:

import simpy

class queue:
    def __init__(self, env):
        self.port = simpy.Resource(env, capacity=1)
        self.buffer = simpy.Container(env, init=0, capacity=1250000000)
        self.mon_proc = env.process(self.monitor_tank(env))
    
    # Added a dummy monitor_tank method since it's referenced but not provided
    def monitor_tank(self, env):
        while True:
            print(f"Current buffer level: {self.buffer.level} at {env.now}")
            yield env.timeout(1)

def Packet(env, id, size, my_queue, time_in_port):
    arrive = env.now
    # Access buffer through the INSTANCE of queue, not the class itself
    yield my_queue.buffer.put(size)
    print(f'packet{id} {size} arriving at {arrive:.2f}')
    
    # Example of using the port resource from the same queue instance
    with my_queue.port.request() as req:
        yield req
        yield env.timeout(time_in_port)
        print(f'packet{id} leaving at {env.now:.2f}')

# Set up the simulation environment
env = simpy.Environment()
# Create an INSTANCE of the queue class (this is where buffer gets initialized)
my_queue = queue(env)

# Spawn sample packet processes
for i in range(3):
    env.process(Packet(env, i, 1000000, my_queue, 2))

env.run(until=10)

Key Changes Made

  • Created an instance of queue called my_queue when setting up the simulation
  • Modified the Packet function to accept my_queue (the instance) instead of just port
  • Changed queue.buffer.put(size) to my_queue.buffer.put(size) to access the instance's buffer attribute

This way, you're correctly accessing the buffer that belongs to your specific queue instance, which was initialized when you ran my_queue = queue(env).

内容的提问来源于stack exchange,提问作者fieq.fikri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:36:03