get/set

Mark McEahern marklists at mceahern.com
Fri May 10 13:03:53 EDT 2002


[William Dode]
> 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 ?

Field descriptors are new with Python 2.2 and require the new-style classes.
To create a new-style class, simple subclass from object (as shown below).
Then, you can create properties...

class Person(object):

  def __init__(self):
    self._first_name = ''

  def get_first_name(self):
    return self._first_name

  def set_first_name(self, value):
    self._first_name = value

  first_name = property(get_first_name, set_first_name)

Obviously, unless I'm doing some validation, there's not much point in using
properties versus just plain old:

class Person:

  def __init__(self):
    self.first_name = ''

p = Person()
p.first_name = "whatever"

// mark






More information about the Python-list mailing list