程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python private variables and private methods

編輯:Python

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 :

  • In the following example, the 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 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved