472,122 Members | 1,478 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,122 software developers and data experts.

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.__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

Sep 2 '08 #1
1 1512
ro*****@river2sea.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
Sep 2 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Rick Austin | last post: by
reply views Thread by =?Utf-8?B?UmljayBHbG9z?= | last post: by
2 posts views Thread by Peter Michaux | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.