[Tutor] Interesting problem
Smith, Jeff
jsmith at medplus.com
Thu Jun 23 22:55:48 CEST 2005
That's what I was looking for. Although I couldn't get the below to
work, I went with a different mod of the original you gave:
def get_props_as_dict(self):
d = dict()
for entry in dir(self.__class__):
if isinstance(getattr(self.__class__, entry), property):
d[entry] = getattr(self, entry)
return d
Thanks!
Jeff
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Kent Johnson
Sent: Thursday, June 23, 2005 4:39 PM
To: Python Tutor
Subject: Re: [Tutor] Interesting problem
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