Jan-11-2019, 06:11 PM
(Jan-11-2019, 10:37 AM)Gribouillis Wrote: I almost never use the double underscore privacy mechanism such as __eggsThe wording privacy mechanism is maybe not best description for the double underscore,as it a has "little" or nothing to do with privacy.
It's really to avoid naming conflicts in subclasses,also called
name mangling
.To take quick tour of
_
and __
.private
and public
variables like Java does,dos not translate directly over to Python.Single
_
class Bar: def __init__(self): self.external = 99 self._internal = 50Use:
>>> obj = Bar() >>> >>> # get >>> obj._internal 50 >>> # set >>> obj._internal = 444 >>> obj._internal 444Have full access to the attribute value of that variable even it with
_
._
just as Waring hint merely an agreed upon convention.Quote:Hey, this isn’t really meant to be a part of the public interface of this class.
Best to leave it alone.
Quote:Nothing is really private in python.
After all, we're all consenting adults here.
Double
__
class Foo: def __init__(self): self.var_1 = 'hello' self.__var_2 = 'egg' # Not private,it's for name mangling when subclass class Bar(Foo): def __init__(self): super().__init__() self.var_1 = 'world' self.__var_2 = 'spam'Use:
>>> obj = Bar() >>> >>> obj.var_1 'world' >>> # var_1 "hello" is overridden and can never be restored >>> >>> obj._Foo__var_2 'egg' >>> obj._Bar__var_2 'spam' >>> # var_2 can not be overridden in subclass,because of name mangling so both "egg" and "spam" can be reachedSo i guess we could say that we private copy of original
egg
,but it still is possible to access or modify a variable that we call private copy