Introduction
Python does not define member functions or properties like C + +, Java, C #, etc. with explicit public, private, or protected keywords, which are identified using the Convention's single underscore "_" and "__" double underscores as a prefix to a function or property. There is a big difference between using a single underline or a double underline.
1. Single underline function or attribute, can be called and accessed in the class definition, the instance of the class can be accessed directly, the subclass can be accessed;
2. Double-underlined functions or properties, which can be called and accessed in the class definition, cannot be accessed directly by an instance of the class, and the subclass is inaccessible.
Note: For double-underlined functions or properties, the Python interpreter uses the method of name obfuscation, turning the private method "__method" into "_classname__method", as shown in the example below.
Private functions and properties of double underlines, not visible in subclasses, no overwrite
Class Base (object): def __private (self): print (' Private value in Base ') def _protected (self): print ( ' protected value in base ') def public (self): print ("Public value in base") Self.__private () self._ Protected () class Derived (Base): def __private (self): print ("Override Private") def _protected (self): Print ("override protected") Print dir (Base) print ("=" *80) d = Derived () d.public () d._protected () d._derived__ Private () print ("=" *80) d.__private ()
The output results are as follows:
>>> [' _base__private ', ' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ' , ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' _protected ', ' Public ']============================================ ====================================public value in baseprivate value in Baseoverride protectedoverride Protectedoverride private================================================================================ Traceback (most recent): File "D:\temp\test.py", line, <module>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Traps for Python class private methods