Getting a *full* list of attrib/methods for a class
Terry Hancock
hancock at anansispaceworks.com
Tue Dec 10 19:29:27 EST 2002
Hi,
I am trying to write a class wrapper, which is actually a bit more
complicated than this, but here's a toy version of what I need to
do:
class Wrapper:
table_name='item'
desc_name='Base Item Class'
def __init__(self, wrapped):
self.url = wrapped.ad_url
kw={}
for key in dir(self):
if key[0]!='_':
kw[key] = getattr(self, key)
self.kw = kw
class to_wrap_class:
ad_url = 'foo'
to_wrap_instance = to_wrap_class()
wrapped = Wrapper(to_wrap_instance)
wrapped.kw
In Python 2.2, this gets what I want:
>>> wrapped.kw
{'url': 'foo', 'desc_name': 'Base Item Class', 'table_name': 'item'}
but not in Python 2.1:
>>> wrapped.kw
{'url': 'foo'}
Although, on reflection, I'm not sure this is for the right reason. I guess
this must be a consequence of Python 2.2's nested scopes. I am constrained
to use 2.1 because of the version of Zope I'm using, in any case.
But what I really wanted was to traverse the class inheritance hierarchy, and
find all methods/attribs inherited by the current object, regardless of
whether they are defined locally in the object, or in one of the object's
parents. I want to do this in exactly the way Python does it, regardless of
what that might actually be (e.g. I know the search order changed between 2.1
and 2.2).
It appears that there is an algorithmic way to do this by explicitly
examining self.__dict__, then self.__class__.__dict__, then
self.__class__.__bases__[0].__dict__ and so on. But this is cumbersome, and
probably error-prone (it means I have to learn what Python does exactly, and
mimic it in my code -- which means I'll be doing it wrong when I do upgrade).
I figured there'd be a built-in or special method to get just this, and when
I experimented with dir() I thought I had it -- but then I realized I was
testing it in Python 2.2! Is there something I just don't know about, or
should I just be writing my own recursive search function to do the job?
Thanks for any pointers,
Terry
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com
"Some things are too important to be taken seriously"
More information about the Python-list
mailing list