I'm not a Python expert so my thoughts might not be exact.
Your
list()
function is returning a reference to the private member. Because the function is a member too, it has access to the array. As a result, the calling side "sees" a reference which is it allowed to use and change.
Do you know C++? It is similar there:
class Test {
public:
Test(int a = 0) { m_a = a; }
int& get() { return m_a; }
private:
int m_a;
};
int main()
{
Test test(1);
test.get() = 2;
printf("%d\n", test.get());
return 0;
}
The solution is to not return the list at all or return a copy of the list (see
Programming FAQ — Python 3.6.6rc1 documentation: How do I copy an object in Python?[
^] ):
return self.__items[:]
return list(self.__items)
return copy.deepcopy(self.__items)
[EDIT]
The best solution would be returning a read only reference like with the C++
const
keyword. But Python does (and will) not support such due to its design and ideology.
With Python, the caller of such functions is responsible for not doing something "wrong" with the returned references. Such should be stated clearly in the documentation for the function.
[/EDIT]