Defining accessor methods

Graham Ashton graham at coms.com
Mon Jun 25 04:48:23 EDT 2001


I've been trying to come up with an idiom for defining accessor methods,
as outlined here:

  http://www.object-arts.com/EducationCentre/Patterns/AccessorMethods.htm

I don't think that my knowledge of Python is quite there yet though. I've
got as far as:

  def my_attribute(self, val=None):
      """Set or return the _my_attribute instance variable."""

      if not val is None: self._my_attribute = val return return
      self._my_attribute

I'd then have code that would use it, like this:

  print "value is: %s" % self.my_attribute()
  self.my_attribute("13")
  print "value is now: %s" % self.my_attribute()

The obvious problem with the above is that you can't use it to set an
attribute to None. The method itself also reads rather strangely. Is there
a better (concise) way to write it so that you can actually pass in None,
and not set the attribute's value to None inadvertently whenever you try
and access it?

I thought of having get_my_attribute() and set_my_attribute() but I don't
really like the idea because it just makes code that uses them more
(unnecessarily) long winded, and the author of the above URL advises
against it (though they don't say why).

I've not noticed any use of accessor methods in sample Python code
(i.e. in books/tutorials); do people use them much in Python?

Thanks.

--
Graham



More information about the Python-list mailing list