Class method ptrs and dictionaries

Shane Hoversten srh232 at nyu.edu
Fri Apr 19 14:16:22 EDT 2002


Hi -

	I was screwing around with python and found, much to my surprise, that 
this does the "right" thing (or at least, the thing I wanted it to do) 
under these circumstances:

---

def nothing():
     print "I'm in nothing."

class foo:
     def bar(self):
         funcDict = {}

         funcDict["funcPtr"] = self.printOne
         func = funcDict["funcPtr"]
         func("Hello, what!")

         funcDict["funcPtr"] = self.printTwo
         func = funcDict["funcPtr"]
         func("Hello, what!", "I say!")

         funcDict["funcPtr"] = nothing
         func = funcDict["funcPtr"]
         func()

     # Class methods to get "pointers" to.

     def printOne(self, word):
         print "printOne: " + word

     def printTwo(self, word1, word2):
         print "printTwo: " + word1 + " " + word2


---

 >>> a = foo.foo()
 >>> a.bar()
printOne: Hello, what!
printTwo: Hello, what! I say!
I'm in nothing.

	My question: how does python "know" that the functions I'm putting in the 
dictionary are class methods that need to be handed a self pointer in 
the first two cases, and not handed one in the third case?  Are these 
issues described somewhere that somebody could point me to so I could 
read about how python handles this behind the scenes?  I did a couple 
quick searches but didn't turn anything up...

Thanks,

Shane




More information about the Python-list mailing list