python The privatization of is to plan for private properties , Avoid irrelevant access 【 If ! I have a wife , You can't directly know who my wife is , You only ask me to know , That is, only I know my private attributes 】
stay python To define private variables and private methods in, you only need to add... Before the variable name or function name "__" Two underscores
When used in methods within a class self.__ Variable name or function name .
actually , If you really want to access private variables and private methods , It's also accessible , Because in fact, the privatization operation only changes the variable or function name :
private_value
Change into _A__private_value
【 namely _ Class name __
Property name 】, But to keep it private , It is not recommended to use this method directly to access ''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
class A:
_private=6
__private_value=5
def __private_func(self):
print("hello")
def get_private_value(self):
return self.__private_value
a=A()
# print(a.__private_value)### Report errors , The property was not found
print(a.get_private_value())
print(a._A__private_value)
Privatize inheritance of variables and methods :【 Subclasses do not inherit private properties of the base class , However, it can still be obtained or forcibly accessed through the functions of the base class 】
class A:
_private=6
__private_value=5
def __private_func(self):
print("hello")
def get_private_value(self):
return self.__private_value
class B(A):
pass
b=B()
# print(b.__private_value)# Report errors
print(b.get_private_value())# You can use the methods of the parent class to get private properties
print(b._A__private_value)# Mandatory access is still possible