3 ms·
Au contraire, double underscore does make it "private". Trying to access a double underscore attribute directly will throw an AttributeError. >>> class Fo
by mdg 17y ago
Au contraire, double underscore does make it "private". Trying to access a double underscore attribute directly will throw an AttributeError.
>>> class Foo(object):
... def __init__(self):
... self.__a = 42
... def look_here(self):
... print self.__a
...
>>> f = Foo()
>>> f.__a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Foo' object has no attribute '__a'
>>> f.look_here()
42
- tkaemming 17y agoA bit off topic, but double underscores don't actually make members in Python truly private, but mangles the attribute name to prevent you from accessing it unless you really need to: http://docs.python.org/tutorial/classes.html#private-variables http://docs.python.org/tutorial/classes.html#private-variabl... >>> class Foo(object): ... def __do_something(self): ... print 'something was done' ... >>> f = Foo() >>> f.__do_something() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute '__do_something' >>> f._Foo__do_something() something was done
- mdg 17y agoYou are 100% correct. This is a good example of Python making it harder for you to do the wrong thing. Sure.. you could access that "private" attribute, but you have to do it in a way that isn't obvious, and definitely more hard to read.