inelegance in calling dynamically created class methods from scripting level

Danny Shevitz shevitz at lanl.gov
Wed Sep 22 19:21:16 EDT 2004


Howdy,

I am trying to call class methods that have been created via a "type"
function. I have enclosed a simplified example that shows what I am trying
to do. In particular I am calling from the scripting level which is in a
different namespace than the dynamically created class. I can call the
method, but only by passing strings and using getattr.I find this inelegant.
I would rather pass a callable object, but cannot figure out how to do this.
So in the example below, I'm trying to get a variant of "myApply" to work.
"myApply2" works but uses strings.

thanks,
Danny

#---%<-------------------------------------------------------------------
# The purpose of this test is to test ways
# to call subclass methods from a scripting level

class Item(object):
 def __init__(self,val):
  self.value=val

 def myPrint(self):
  print self.value

class DoSomething(object):
 def __init__(self, dict):
  ItemChild = type('Item_child',(Item,),dict)
  self.childClass=ItemChild
  # create an example list
  self.itemList = []
  for i in range(5):
   self.itemList.append(ItemChild(i))

 # can't get to work with callable objects
 def myApply(self, whatever):
  for item in self.itemList:
   whatever(item)

 # works with string arguments
 def myApply2(self, whatever):
  func = getattr(self.childClass,whatever)
  for item in self.itemList:
   func(item)

##########################################################
# begin scripting code
##########################################################

# child method to be spliced in
def reset(self,val=0):
 self.value=val

# construct a DoSomething class
ds = DoSomething({'hoopty':reset})

# I am trying to get something like this working...
# ds.myApply(???something callable???) Can't get to work!

# control operation from the scripting level
ds.myApply2('myPrint')
ds.myApply2('hoopty')
ds.myApply2('myPrint')






More information about the Python-list mailing list