__dict__ for instances?

half.italian at gmail.com half.italian at gmail.com
Sun May 13 00:04:31 EDT 2007


On May 12, 5:20 pm, Ivan Voras <ivoras at __fer.hr__> wrote:
> While using PyGTK, I want to try and define signal handlers
> automagically, without explicitly writing the long dictionary (i.e. I
> want to use signal_autoconnect()).
>
> To do this, I need something that will inspect the current "self" and
> return a dictionary that looks like:
>
> {
>   "method_name" : self.method_name
>
> }
>
> Class.__dict__ does something very similar, but when I use it, either
> I'm doing something wrong or it doesn't return methods bound to "self",
> and python complains a wrong number of arguments is being passed to the
> methods (one instead of two).
>
> instance.__dict__ on the other hand returns an empty dictionary.
>
> This looks like it should be easy, but I can't find the solution :(
>
> --
> (\__/)
> (O.o)
> (> < )
>
> This is Bunny.
> Copy Bunny into your signature to help him on his way to world domination!
>
>  signature.asc
> 1KDownload

I think you want "dir(instance)"  __dict__ returns the instance
variables and values as a dictionary, but doesn't return methods.
dir() returns a list of the instance's methods and variables.  Then
you'd need to iterate over the list with type() looking for instance
methods

instance = Class.Class()
dict = {}
methods = [f for f in dir(instance) if str(type(instance.f)) == "<type
'instancemethod'>"]
for m in methods:
    dict[m.name] = m

The above is untested. I'm sure there is a better way to do this.

~Sean




More information about the Python-list mailing list