[Tutor] Accessing class attributes: use methods only?
kent37 at tds.net
Wed Feb 14 19:01:14 CET 2007
Dave Kuhlman wrote:
> Some of us old school types feel that properties are non-Pythonic.
> They are a way to write code that does something that it does not
> look like that code is doing. It hides your intend. So, it is not
> "Explicit is better than implicit."
> - Tim Peters
> (see http://www.python.org/dev/peps/pep-0020/)
> In other words, properties are a way of writing code that appears
> harmless, for example:
> temp = weather.temperature
> weather.temperature = temp
> but making it do arbitrary, sneaky, gratuitous, and egregious things.
And this is different how from what is available without properties?
__setattr__ and __getattr__ hooks have been available at least since
Python 1.4. New-style classes add __getattribute__. All of these exist
so you can make attribute access do useful things, or if you want,
arbitrary, sneaky, gratuitous, and egregious things.
Functions *are* descriptors (the underlying mechanism behind properties)
since Python 2.2. The magic that makes bound and unbound methods is in
the __get__() method of the function. When you invoke
weather.getTemperature() you are essentially invoking a property to get
the getTemperature() method. Which is pretty sneaky ;-)
Of course you can also change the meaning of a + b, c, etc if you like.
Because it is highly dynamic and exposes much of its internal
mechanisms, Python gives the programmer great latitude to do stupid
things in a wide variety of ways. This is generally considered a feature.
More information about the Tutor