determining instance attributes
Richie Hindle
richie at entrian.com
Fri Jul 5 06:11:52 EDT 2002
> how can an instance easily find out all its non-method instance attributes?
This finds all non-callable instance attributes. That means it won't
find inner classes, but I'm guessing you didn't want those anyway:
>>> class Test:
... def __init__( self ):
... self.attribute = 1
...
... def findNonMethodAttributes( self ):
... names = []
... for name, attribute in self.__dict__.items():
... if not hasattr( attribute, '__call__' ):
... names.append( name )
... return names
...
>>>
>>> test = Test()
>>> print test.findNonMethodAttributes()
['attribute']
>>>
If you're using Python 2.x and you're a fan of list comprehensions:
def findNonMethodAttributes( self ):
return [ name for name, attribute in self.__dict__.items() if not hasattr( attribute, '__call__' ) ]
--
Richie Hindle
richie at entrian.com
More information about the Python-list
mailing list