[Tutor] Interesting problem
Smith, Jeff
jsmith at medplus.com
Thu Jun 23 21:24:59 CEST 2005
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().
For those who are interested, the dictionary created by
getprops_as_dict() will be fed to string.Template.substitute
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 3:17 PM
To: Python Tutor
Subject: Re: [Tutor] Interesting problem
Still not that clear. What do you want to see when you call
MyClass().getprops_as_dict() ?
Maybe this will give you some ideas:
>>> class MyClass:
... def __init__(self, val1, val2):
... self._var1 = val1
... self._var2 = val2
... var1 = property(lambda s: s._var1)
... var2 = property(lambda s: s._var2)
... def _var3(self):
... return self._var1 + self._var2
... var3 = property(_var3)
... def getprops_as_dict(self):
... d = dict(self.__dict__)
... return d
...
>>> m=MyClass(1,2)
Using just m.__dict__:
>>> m.getprops_as_dict()
{'_var2': 2, '_var1': 1}
The inspect module might be some help:
>>> import inspect
>>> for k, v in inspect.getmembers(m):
... print k, '=', v
...
__doc__ = None
__init__ = <bound method MyClass.__init__ of <__main__.MyClass instance
at 0x008DD918>> __module__ = __main__ _var1 = 1 _var2 = 2 _var3 = <bound
method MyClass._var3 of <__main__.MyClass instance at 0x008DD918>>
getprops_as_dict = <bound method MyClass.getprops_as_dict of
<__main__.MyClass instance at 0x008DD918>> var1 = 1 var2 = 2 var3 = 3
This inspects the class for actual properties and shows their values. It
won't print simple attributes (in m.__dict__) or attributes defined by
user-defined descriptors though:
>>> for p in dir(m.__class__):
... pp = getattr(m.__class__, p)
... if isinstance(pp, property):
... print p, '=', getattr(m, p)
...
var1 = 1
var2 = 2
var3 = 3
Kent
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list