use member functions to access data in Python classes?
sross at connectmail.carleton.ca
Wed Jun 18 19:40:54 CEST 2003
<beliavsky at aol.com> wrote in message
news:3064b51d.0306180815.75869d6f at posting.google.com...
> In C++, it is generally recommended to declare the data within a class
> private and to access the data using member functions. Do experienced
> Python programmers usually use member functions to access data within
> classes, or do they access the data directly?
Depends on the programmer, but I'd say most will just access the data
directly. Personally, if making get/set methods amounts to no more than:
self.foo = value
then I will just use 'foo' directly, e.g.
# instance.getfoo() is just
# and instance.setfoo(value) is just
instance.foo = value
If, however, the get and/or set methods will be doing something more complex
than what's shown above, I'll use properties, and make my data private,
Even in C++/C#/Java, et al, if you have a private instance attribute, but
you have only the simple get/set methods shown above, you may as well have
just made your instance attribute public and used it directly. The reason
you probably shouldn't do that is because the way that your instance
attribute should be accessed or modified may change in the future. If you've
used get/set methods you can just change the behaviour in those methods
rather than everywhere your instance attribute is used. Which seems like a
pretty good reason to be using get/set after all <wink>.
Python (and C#) provide(s) properties which give you the benefit of
encapsulating your data while still permitting you to code as though you
where using your data directly. There's not much difference there really,
just that one form looks cleaner than the other (instance.getfoo() vs.
instance.foo). Still, I prefer properties to get/set for precisely that
More information about the Python-list