Getting a list of member functions

Christian Tismer tismer at tismer.com
Fri Dec 15 06:12:15 EST 2000


Jay O'Connor wrote:
> 
> Hi,
> 
>         I'm trying to get a list of the member functions for an object.  I would think __members__ or __methods__ would work
> 
> Here's what I'm getting

[of course not working...]

> This is on Pythong 1.5.2
> 
> Did I miss something?
> 
> I know I could probably loop through the classes __dict__ and pull out the functions, but that's kinda kludgey and would miss instance specific methods

Classes do not implement __members__ and __methods__ automagically,
but you can do this yourself.

If you want to provide static members for instance, just put
a list
  __members__ = ["var1", "var2", "var3"]
into your class.
If you want to make this more dynamic or instance specific,
it is a little more complicated, since you then have to
overwrite __getattr__ and compute the __members__ attribute
on-the-fly.

>>> class demo:
... 	def __init__(self, **vars):
... 		self.__dict__.update(vars)
... 	def __getattr__(self, key):
... 		if key=="__members__":
... 			return self.__dict__.keys()
... 		raise AttributeError, key
... 	
>>> x=demo(a=5, b=7, c=42)
>>> x.__members__
['b', 'c', 'a']
>>> x.x=0
>>> x.__members__
['b', 'c', 'x', 'a']
>>> 

Of course this gets more clumsy if you also have to support
instance-specific methods. But I doubt that these are
so urgent to have at all.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list