Referring to method of a class without instance?

Gordon McMillan gmcm at hypernet.com
Sun Jul 2 23:40:57 EDT 2000


gmol at my-deja.com wrote in <8jou05$mei$1 at nnrp1.deja.com>:

>In my application I use the observer/observable pattern..question
>I hate duplicating the information of what was changed by making up a
>new message type (global message variables or strings) and using tonnes
>of if-else clauses.  I'd rather just tell my observer which method was
>called and the arguments passed to it.  (I.e. I have atoms in 3d space,
>when setPosition(position) is called I would just like to tell whoever
>is interested that setPosition was called with the argument position))
>
>Problem, how do I refer to the method of a given class without making an
>instance?  Like suppose I notify my observers by giving the funciton
>address and arguments, I would like the observer to have a dictionary
>whose keys are methods
>
>class Atom:
>....
>
>
>class myobserver:
>...
>
>   updateTable={....
>       Atom.setPosition:handle_A_setPositio
>    }
>...
>
>Hmm I have also just realized that given
>class A:
> def __init__(self...)
>
>a=A()
>
>a.init is not equal to A.__methods__['__init__']
>
>Hmmm I thought that would be the worst way I could do it, but I guess I
>couldn't if I wanted to...

That's right: a.__init__ is a bound method, while A.__init__ is an unbound 
method. You can get to the latter from the former by:
 self.__class__.__init__
or more directly (of course) 
  A.__init__

But you might be headed for trouble. For example, you might later add a 
class Molecule with a setPosition method. Now you have to go through all 
your observers and update their dispatch tables. IOW, you're tightly 
coupling your observers to your observables.

OTOH, A.__init__ and a.__init__ both have __name__ attributes with 
singularly unexciting values <wink>. Then you just have to be sure you 
don't get sloppy and write Molecule.setPos(....).

Of course, since there's no special name for "the currently executing 
method", in effect you're still maintaining a global table of message 
identifiers.

- Gordon



More information about the Python-list mailing list