Referring to method of a class without instance?
Daniel Berlin
dberlin at cygnus.com
Sun Jul 2 23:09:14 EDT 2000
gmol at my-deja.com writes:
> 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...
>
> Any thoughts or better general solution would be appreciated...
>
This is a simple problem.
Try A.__init__
>>> class B:
... def __init__(self):
... pass
...
>>> B.__init__
<unbound method B.__init__>
>>> __
If you try to call it without a class instance as the first parameter, you'll get an error.
>>> B.__init__(5)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: unbound method must be called with class instance 1st argument
Otherwise, it'll work fine.
>>> B.__init__(B())
HTH,
Dan
More information about the Python-list
mailing list