synthetic properties

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rowland@river2sea.org

    synthetic properties

    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.__ini t__? 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 ObjectivePython Object( type ) :

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

    def __init__( cls, name, bases, dct ) :
    #print "Initializi ng 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__ = ObjectivePython Object


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

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


    Thanks,
    Rowland

  • Diez B. Roggisch

    #2
    Re: synthetic properties

    rowland@river2s ea.org schrieb:
    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.
    Why on earth do you want to do that? The reason synthesized properties
    exist in ObjC is simply that to expose properties for key-value-coding,
    one needs the getter/setters. But mostly these are boilerplate, so apple
    introduced the @synthesized-annotation.

    But in python, you don't need that. You use simple attributes. In the
    very moment you need logic attached, use the builtin property to do so.




    Diez

    Comment

    Working...