http://qs321.pair.com?node_id=11106247


in reply to Language design: direct attribute access and postponed mutators (Perl Vs Python)

Although in Python attributes could can be accessed directly, it also has the double underscore mechanism for providing a basic level of attribute hiding e.g.
% cat stack.py class Stack(): def __init__(self): self.__items = [] def __repr__(self): return str(self.__items) def push(self, x): self.__items.append(x) def pop(self): self.__items.pop() % python3 Python 3.7.4 (default, Sep 7 2019, 18:27:02) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from stack import Stack >>> s = Stack() >>> s.push(42) >>> s [42] >>> s.__items Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Stack' object has no attribute '__items' >>>
I.e. prepending two underscores to an attribute name makes it harder to use from outside the class.
  • Comment on Re: Language design: direct attribute access and postponed mutators (Perl Vs Python)
  • Download Code

Replies are listed 'Best First'.
Re^2: Language design: direct attribute access and postponed mutators (Perl Vs Python)
by LanX (Saint) on Sep 16, 2019 at 20:11 UTC
    True, but the OP wasn't about hiding private attributes, but about maintaining public attributes.

    Once you've exposed an attribute in the API and and external code is accessing it directly, it becomes complicated to realize "a man in the middle" layer functioning as getter and setters.

    Classic (a bit contrived) example is an attribute .name which needs at some point to evolve to a getter name() returning a concat of .firstname and .lastname (and probably .middlename) without breaking old code.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice