[Tutor] Interesting problem

Kent Johnson kent37 at tds.net
Thu Jun 23 21:16:48 CEST 2005


Smith, Jeff wrote:
> I can see I wasn't clear :-)
> 
> Here's the basic framework of what I'm looking for.  Needless to say,
> this is just an example and not the real problem which is quite
> complicated and includes multiple classes.
> 
> What I'm looking for is the actual implementation of get_props_as_dict
> which I've written here as pseudo-code
> 
> class MyClass:
> 	def __init__(self):
> 		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()
> 		for prop in properties:
> 			d[prop_name] = prop_value
> 		return d

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



More information about the Tutor mailing list