Using Python properties has advantages over the direct access you offer.
Consider the implementation
class Foo(object): def __init__(self): self.bar = ...
against.
class Foo(object): def __init__(self): self._bar = ... ... @property def bar(self): return self._bar
Suppose you have foo = Foo() . In the first case, you access the element as foo.bar . That means you can do
print foo.bar foo.bar = 3
Ie, you cannot restrict the modification of bar . In the latter case, however, relying on an agreement not to have access to things prefixed with _ , admittedly, you can do
print foo.bar
but
foo.bar = 3
will raise an exception.
In addition, using property definitions , you can control the change of bar , as well as perform checks and other interesting things:
class Foo(object): def __init__(self): self._bar = ... ... @property def bar(self): return self._bar @bar.setter def bar(self, value): if something_of_value(value): raise Whatever self._bar = value
Ami tavory
source share