Search code examples
pythonclassattributeerrorsimpy

Python AttributeError: class has no attribute


I have this code with a class queue which consist of simpy Resource and Container (buffer):

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

But when I want to use the class and it's attribute buffer using

def Packet(env, id, size, port, time_in_port):

    arrive = env.now
    yield queue.buffer.put(size)
    print('packet%s %s arriving at %lf' % (id, size, arrive))

    with port.request() as req:
        yield req

        tip = random.expovariate(1/time_in_port)
        yield env.timeout(tip)
        amount = size
        yield queue.buffer.get(amount)
        print('packet%s %s depart at %lf' % (id, size, env.now))

I'm getting the following error when calling queue.buffer

AttributeError: class queue has no attribute 'buffer'

Mind to explain why I can't use the attribute from the class? Thanks.


Solution

  • If queue is your class, and it has an instance attribute of buffer, then you can access buffer through instances of your class, not the class itself.

    E.g.

    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))
    
    def Packet(env, id, size, port, time_in_port):
        queue = Queue(env) # instantiate your class
        ...
        # Make use of queue.buffer