[Tutor] Interesting problem

Chuck Allison chuck at freshsources.com
Wed Jun 29 01:10:08 CEST 2005


I may be missing something, but isn't this what __dict__ does? Just 
return self.__dict__. This is an old message, so this may have mentioned 
already. Sorry if that's the case. I'm a little behind.

Kent Johnson wrote:

>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))
>    )
>
>Kent
>
>  
>
>>For those who are interested, the dictionary created by
>>getprops_as_dict() will be fed to string.Template.substitute
>>
>>Jeff
>>    
>>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>


More information about the Tutor mailing list