March 17, 2008

Python getters and setters

Filed under: dev, python — michaelangela @ 7:58 am

From the python guru himself, Guido van Rossum, we have a bit on his take of python getters and setters…

[Python-Dev] Declaring setters with getters

I've come up with a relatively unobtrusive pattern for defining
setters. Given the following definition:

def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.__get__, func, func, prop.__doc__)
return helper

we can declare getters and setters as follows:

class C(object):

_encoding = None

def encoding(self):
return self._encoding

def encoding(self, value=None):
if value is not None:
unicode("0", value) # Test it
self._encoding = value

c = C()
c.encoding = "ascii"
c.encoding = "invalid" # Fails

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: