Main Content

Python Properties - how and why

Archive - Originally posted on "The Horse's Mouth" - 2013-05-18 09:58:09 - Graham Ellis

When you're being taught Object Oriented Programming, you'll usually be encouraged to access all the various elements within each object through methods rather than by going directly at the variables that hold properties within the object directly. And yet this will often result (depending on the language) in you having to write a whole series of short property accessor functions. Here's an example of the sort of thing that I mean in Python:

  def setPubyear(self,year):
    self.pubyear = year
  
  def getPubyear(self):
    return self.pubyear


The reason you're taught (and I, too, teach) the use of methods rather than direct variable access is because it gives you a far greater flexibility later on. Hard coding variable names within objects into applications makes those variables a part of the API (Application Program Interface) and the provider of the class is then constrained in future enhancements. And that's a double constraint, because there's no intermediate code layer in which features that may become necessary (capitalisation, space trimming, logging access etc) can be added. In other words - by directly accessing variables, you're building up a potential update and maintenance problem.

But wouldn't it be nice in the application to be able to access properties / attributes of an object as if they were simple variables, rather than having to use the extended syntax of calling setter and getter methods? Well - in Python you can, using a property. Here's how it works:

• within your class, you declare that variable name = property (getter, setter, deleter, doc) where getter, setter and deleter are the methods to run when a property is called up. You'll always need to provide a getter (otherwise there's little point in trying to define a property), but the other parameters are optional.

• within your application, you access the property as if it was a variable within the object, but within the class it gets diverted to the code.

Example:

Defining a property:
  author = property(lambda x:x._author , None)

Making use of that property:
  print nineteen.author

Complete example - [here] from the course I've been giving in Oxford for the last couple of days. And that gives me an excuse to illustrate my post with a picture I took when walking into the location at which I was training along the River Thames