How to get/set class attributes in Python

Terry Hancock hancock at anansispaceworks.com
Mon Jun 13 14:41:48 EDT 2005


I really think the problem is that you are trying to use 
techniques whose only reason for existing is that they make 
up for deficiencies in other languages:

For example, the *reason* for the Java or C++ use of get/set
methods is to allow for the future possibility of needing to
make those operations dynamic.  Python solves this by 
allowing you to create get/set methods *only when needed*
by using "properties", using exactly the same interface as
provided by ordinary attributes. Thus there is no need to
artificially add get/set methods in the general case.

This results in much cleaner and more concise code.

The *reason* for taking so much care that a variable is of 
the right type in classes in C++ or Java is because the 
program will crash if they are not.  In Python, you would 
be better served to:

1) Assume the variables are of a sensible type (not 
necessarily the one you expected, though), and provide
exception handling to catch the case where their interface
does not match what you expect.

2) Check for the specific interface methods that you need,
only  (if all you plan to do is read from a "file", you 
shouldn't worry about whether the "file" object you've been 
handed actually has a "write" method or not).
This is often called "duck typing".

3) Use "interfaces" (either from Zope or PyProtocols) to 
specify the required *behavior* (not type).

Let's face it -- should it matter if you "are a programmer" 
or only if you "can program"?  This is the difference in
philosophy behind a dynamically-typed language like
Python and a statically typed one like Java.


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list