get/set

Gerhard Häring gerhard at bigfoot.de
Fri May 10 13:27:16 EDT 2002


William Dode wrote in comp.lang.python:
> hi,
> 
> coming from java, i use to do a lot of get set method and make all the
> variable as private.
> 
> class Toto:
> 	def getA(self): return self._a
> 	def setA(self,v): self._a=v
> 	...
> 
> Shall i do like that in python ?

I think you don't need this boilerplate code most of the time. Since
Python 2.2, however, you can mimic the Java behaviour without
resorting to __getattr__/__setattr__. The pyhton.org website with
Guido's introduction to 2.2 features currently seems to be down, but
you can look here for some basic intro for 2.2 features:

http://www.amk.ca/python/2.2/

Your example could then look like:

class Toto(object):
    __slots__ = ["_a"]

    def __init__(self):
        self._a = 5

    def set_a(self, val):
        if val < 5 or val > 10:
            raise ValueError, "val must be in [5;10]"
        self._a = val

    def get_a(self):
        return self._a

    # Third argument is for attribute deletion; None means cannot delete attribute
    a = property(get_a, set_a, None)

x = Toto()
print x.a
x.a = 10
x.a = 11        # raises ValueError
x.b = 5         # raises AttributeError; no such attribute

It also has the advantage that it can be used with GPL software ;-)

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list