accessor/mutator functions

Simon Wittber simonwittber at gmail.com
Fri Feb 25 03:53:36 EST 2005


> My questions are:
> a) Are the three things above considered pythonic?

Python uses a function called 'property to achieve the same effect.
This example is taken from the documentation:

    class C(object):
        def __init__(self):
            self.__x = 0
        def getx(self):
            return self.__x
        def setx(self, x):
            if x < 0: x = 0
            self.__x = x
        x = property(getx, setx)


In the above example, "C().x" would invoke and return the result of
.getx (the accessor), and "C().x = 10" would invoke .setx (the
mutator).

Are they considered Pythonic? Well, It depends on how they are used.
If you are using properties to perform some kind of type checking...
then the answer is probably No.

I've found that they are quite useful for implementing lazy evaluation
of attributes, which I would consider quite Pythonic.

Sw.



More information about the Python-list mailing list