synthetic properties

rowland at river2sea.org rowland at river2sea.org
Tue Sep 2 21:48:05 CEST 2008


I'm trying to come up with solution for adding synthetic properties to
python, similar to synthetic properties in Objective-C.

I'm playing around with doing this in a MetaClass.  I can dynamically
create the attributes that will back the property, but I'm having
trouble figuring out how to dynamically generate get/set methods to
pass to the built-in property() function.

Is it possible to define a lambda or a callable object that will act
as a getter method (or setter, that takes a value argument) during
MetaClass.__init__?  The hard part I'm guessing is getting the current
instance passed into the getter.  This is my first foray into
MetaClasses and dynamic functions/methods so any pointers are greatly
appreciated.


class ObjectivePythonObject( type ) :

    def __new__( cls, name, bases, dct ) :
        #print "Allocating memory for class", name
        return type.__new__(cls, name, bases, dct )

    def __init__( cls, name, bases, dct ) :
        #print "Initializing class", name
        for propertyInfo in cls.synthesized :
            property = propertyInfo[ 0 ]
            defaultValue = propertyInfo[ 1 ]
            print property
            setattr( cls, '_' + property, defaultValue )
            # Create property with get/set methods...

class Person( object ) :

    __metaclass__ = ObjectivePythonObject


    synthesized = [ ( 'name', 'BobC' ),
                    ( 'age', '48' ) ]

    def __init__( self ) :
        print self._name
        print self._age


Thanks,
Rowland




More information about the Python-list mailing list