[Tutor] viewing attributes of objects in a class

Erik Price erikprice@mac.com
Sat Mar 8 12:11:01 2003


On Sunday, March 9, 2003, at 10:31  AM, reavey wrote:

> >>> class = Object:
>             pass
> >>>personA = Object()
> >>> personA.name = "Ann"
> >>>personA.age = 31
> is there a list of this object with its attributes which can be 
> retrieved,
> like personA.inspect?

Yes, just remember that in Python, a user-defined class/object is 
really just a high-tech dictionary.  Every attribute of the 
class/object is a key of the dictionary.  When you set an attribute, 
you're setting a key/value in the dictionary.  Use the __dict__ method 
to see these attributes:

 >>> class villain:
...  def __init__(self, name, henchman, nemesis):
...   self.name = name
...   self.henchman = henchman
...   self.nemesis = nemesis
...
 >>> skeletor = villain('Skeletor', 'Beast-Man', 'He-Man')
 >>> skeletor.__dict__
{'nemesis': 'He-Man', 'henchman': 'Beast-Man', 'name': 'Skeletor'}

The only real difference is that when you attempt to retrieve an 
attribute, the processor will check the instance for an attribute, and 
if it doesn't find it will continue to check the class (for a 
class-wide attribute), and if not found then will continue to check any 
base classes.

I may be oversimplifying something but that's the general gist of it.


Erik





-- 
Erik Price

email: erikprice@mac.com
jabber: erikprice@jabber.org