views:

225

answers:

5

I'm doing it like:

def set_property(property,value):  
def get_property(property):  

or

object.property = value  
value = object.property

I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.

+6  A: 

Check out the "@property" decorator: http://docs.python.org/library/functions.html#property.

Kevin Little
Fantastic! Thank you!
Jorge
Thanks, @TheMachineCharmer -- I should have done that :}
Kevin Little
+14  A: 

The Pythonic way is to not use them. If you must have them then hide them behind a property.

Ignacio Vazquez-Abrams
Required reading: http://dirtsimple.org/2004/12/python-is-not-java.html
Ned Deily
Required viewing: http://www.archive.org/details/SeanKellyRecoveryfromAddiction
Ignacio Vazquez-Abrams
+2  A: 

Here's a pretty good blog post on properties (getters, setters) in Python:
The Python Property Builtin

ars
A: 
In [1]: class test(object):
    def __init__(self):
        self.pants = 'pants'
    @property
    def p(self):
        return self.pants
    @p.setter
    def p(self, value):
        self.pants = value * 2
   ....: 
In [2]: t = test()
In [3]: t.p
Out[3]: 'pants'
In [4]: t.p = 10
In [5]: t.p
Out[5]: 20
Autoplectic
+2  A: 

Try this: Python Property

The sample code is:


class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        print "getter of x called"
        return self._x

    @x.setter
    def x(self, value):
        print "setter of x called"
        self._x = value

    @x.deleter
    def x(self):
        print "deleter of x called"
        del self._x
Grissiom