0

I'm rather new to Python. To optimize my code, I programmed something like this:

class MyObject:
  #class definition

myObject1=MyObject()
myObject2=MyObject()
myObject3=MyObject()

def initObject(ix):
  theObject=eval("myObject%d" % (ix))
  #do object initialization
  action1(theObject)
  action2(theObject)

def action1(obj):
  #do something with obj

def action2(obj):
  #do something more with obj

That way I have only one code to maintaine and that code works on every object instance. This code seems to work, but I'm not sure it is the best practice and moreover I'm not sure there could be situations where bugs might arise that are difficult to debug.

Any suggestion is welcome.

Thanks in advance

Edit:

To answer jonrsharpe: I don't want to create a

variable number of variables

I have a fixed number of global variables whose names differ from each other for an index. I need to call the same routines on them, passing only the index to the routines like in the following snippet:

for ix in range(1,4):
  initObject(ix)
user1737538
  • 497
  • 2
  • 7
  • 16
  • 1
    [Use a list](https://docs.python.org/2/tutorial/introduction.html#lists). – kennytm Mar 14 '17 at 07:58
  • 1
    Why not passing the real instance? Also you could use [`globals()`](http://www.diveintopython.net/html_processing/locals_and_globals.html) to get the instance – urban Mar 14 '17 at 07:59
  • initObject is called in a for loop like this `for ix in range(1,4): initObject(ix)` That's the primary reason I chose this way. – user1737538 Mar 14 '17 at 08:18

0 Answers0