«
»

Python, Tech Tip

The Python Property

06.16.08 | Comment?

One of my projects this summer has been to learn Python. I want to be able to use it to replace Matlab and LabView. I may try to write a little more of the how and why later. I have been learning a great deal about Python in the last month or so and thought maybe I would try posting solutions to the little frustrations I find in hopes that it may save someone else the frustration.

So here is #1: property()

This is a cool feature of Python, that the typical getter/setter patterns in C++ classes can be implemented easily and quickly. But here is the problem:
class C:

def __init__(self) : self.__x = 0
def getx(self):

print "(Fetch)",
return self.__x

def set_trace(self, value):

self.__x = value

x = property(getx, set_trace)

foo = C()
print “foo.x = “, foo.x
foo.x = 1
print “foo.x = “, foo.x
foo.x = 3
print “foo.x = “, foo.x
>>foo.x = (Fetch) 0
>>foo.x = 1
>>foo.x = 3

This doesn’t work, getx() is only called the first time. After that, the foo.x = 1 assignment overwrites the getter/setter object. Perhaps the solution is obvious to Python guru’s but it wasn’t to me. However, I finally discovered that for properties to work C must explicitly inheret from the object class. Simply change the first line to:
class C(object):
and wala! You get:

>>foo.x = (Fetch) 0
>>foo.x = (Fetch) 1
>>foo.x = (Fetch) 3

Hope that helps!

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

You must be logged in to post a comment.


«
»