[Tutor] Interesting problem

Kent Johnson kent37 at tds.net
Thu Jun 23 22:38:39 CEST 2005

Smith, Jeff wrote:
> Here would be the usage:
> myinst = MyClass()
> print myinst.getprops_as_dict()
> would print
> {'var1': 1, 'var2': 2, 'var3': 3}
> Needless to say I want the instance values which might be different for
> each instance.  I know that I could code it brute force, but I want to
> be able to add properties without having to remember to update
> getprops_as_dict().

OK, so will a variation on my last recipe work? This looks for property attributes of the class and gets the corresponding property on the instance:
  def getprops_as_dict(self):
    return dict(pname, getattr(self, pname) 
      for pname in dir(self.__class__) 
        if isinstance(getattr(self.__class__, pname), property))


> For those who are interested, the dictionary created by
> getprops_as_dict() will be fed to string.Template.substitute
> Jeff

More information about the Tutor mailing list