accessing class data members
Stephen D Evans
stevee at recombinant.demon.co.uk
Tue Jul 3 15:08:18 EDT 2001
Curtis,
It's a question of style/performance. Neither obj.temperature nor
obj.get_temperature() are necessarily better. Accessing a class variable
directly or indirectly via a function are both valid and have
advantages/disadvantages depending on the language/task.
For indirect variable access via a function:
* In a compiled language the indirect access via a function call can be
optimised away by the compiler, so there may be no loss of runtime
speed.
* In Python there is the overhead of a function call, therefore
potentially slower.
* If the function does not exist, the code crashes.
* Debugging is easier as all accesses to the variable can be
trapped/traced.
For direct variable access:
* In Python this is quicker.
* It is possible to set a 'typo', e.g. obj.temperature_oops = t without
any complaint, but not (always) retrieve one e.g. t =
obj.temperature_oops may or may not work.
* Possibly harder to debug the code.
For quick and dirty debugging in Python it is possible to override the
__getattr__ and __setattr__ class methods and thus provide the equivalent
of obj.get_temperature() and obj.set_temperature(t) while using
obj.temperature in the code. Use has to be made of the
__getattr__/__setattr__ asymmetry.
class UpperClassTwitOfTheYear:
"""An example for debugging only"""
def __setattr__(self, name, value):
if name == 'temperature':
name = 'hidden_temperature' # rename, place debugging code here
self.__dict__[name] = value
def __getattr__(self, name):
assert name=='temperature' # should only be called for this
return self.__dict__['hidden_temperature']
Having looked at a lot of Python code and programmed in Python regularly
for over a year, I generally use direct access to the class variable in
Python i.e. obj.temperature
Stephen D Evans
Curtis Jensen wrote:
> In many OO languages, and theory, it is often the case that when you
> want to know the value of some data member, that a function is written
> to return that value. However, in Python it seems that people just
> access the data member directly.
>
> for example:
> if there were a class that represented a physical object. In the class
> there were data members that held the objects temperature and location.
> If I wanted to know the temperature of an object, I could just use
> obj.temperature. Though in other languages, the convention seems to
> call a function that returns the value, like: obj.get_temperature.
>
> Which is better?
>
> --
> Curtis Jensen
> cjensen at bioeng.ucsd.edu
> http://www-bioeng.ucsd.edu/~cjensen/
> FAX (425) 740-1451
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010703/ce95ec10/attachment.html>
More information about the Python-list
mailing list