Search code examples
pythoninstances

How to call a different instance of the same class in python?


I am new to Python. I am writing a simulation in SimPy to model a production line, which looks like: Machine 1 -> Buffer 1 -> Machine 2 -> Buffer 2 -> and so on..

My question: I have a class, Machine, of which there are several instances. Suppose that the current instance is Machine 2. The methods of this instance affect the states of Machines 1 and 3. For ex: if Buffer 2 was empty then Machine 3 is idle. But when Machine 2 puts a part in Buffer 2, Machine 3 should be activated.

So, what is the way to refer to different instances of the same class from any given instance of that class? Also, slightly different question: What is the way to call an object (Buffers 1 and 2, in this case) from the current instance of another class?

Edit: Edited to add more clarity about the system.


Solution

  • It is not common for instances of a class to know about other instances of the class.

    I would recommend you keep some sort of collection of instances in your class itself, and use the class to look up the instances:

    class Machine(object):
        lst = []
        def __init__(self, name):
            self.name = name
            self.id = len(Machine.lst)
            Machine.lst.append(self)
    
    m0 = Machine("zero")
    m1 = Machine("one")
    
    print(Machine.lst[1].name)  # prints "one"