Python AttributeError求助:调用queue类buffer属性时提示无此属性
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:
- Create an instance of your
queueclass first - Pass that instance (not just individual attributes like
port) to yourPacketfunction, then accessbufferthrough 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
queuecalledmy_queuewhen setting up the simulation - Modified the
Packetfunction to acceptmy_queue(the instance) instead of justport - Changed
queue.buffer.put(size)tomy_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

