listing all property variables of a class instance

Jay Loden python at jayloden.com
Mon Jun 25 19:20:27 CEST 2007


Neil Cerutti wrote:
>> Is there a way to write a method that would list automatically
>> all the variables defined as a property (say by printing their
>> docstring and/ or their value), and only those variables?
> 
> This is off the cuff. There's likely a better way.
> 
> for k, v in MyClass.__dict__.iteritems():
>   if isinstance(v, property):
>     print k, v.__doc__
> 

The only way I could get this to work was to change the way the properties were defined/initalized: 

#!/usr/bin/python

class MyClass(object):

  def __init__(self):
    self.some_variable = 42
    self._a = None
    self._b = "pi"
    self.a = property(self.get_a,  self.set_a, None, "a is a property")
    self.b = property(self.get_b,  self.set_b, None, "b is a property")

  def get_a(self):
    return self._a
  def set_a(self, value):
    self._a = value

  def get_b(self):
    return self._b
  def set_b(self, value):
    self._b = value


test = MyClass()
for k,v in test.__dict__.iteritems():
  if isinstance(v, property):
    print k, v.__doc__



More information about the Python-list mailing list