Skip to content
Advertisement

How to trigger a method in 2 instances of the same class object in Python?

I had 2 instances (st0, st1) of the same class (State) in which has 2 methods. Somehow when st0.loc_st() is called, I want that st1.rem_st() to be automatically triggered. How can I achieve that purpose with Python OOP? Sorry the code looks a bit naive, but it’s a simplified model saves the reading effort.

JavaScript

Advertisement

Answer

If you want the method of every instances to be called, you can just add a list to the class and iterate over all the instances and call their method:

JavaScript

Or you could add an array of instances to the class constructor. When the method gets called on an instance you could then iterate over all the instances in that array and call the method:

JavaScript

In case you want to initialize st0 first, you could either add an addInstance method to the class, which would add a instance to the instances array of that instance:

JavaScript

Or you could also add a reference to the constructor, so that the instance itself gets added to the instances of that reference.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement