This example analyzes the private properties and methods of Python. Share to everyone for your reference. The implementation methods are as follows:
Python's default member functions and member variables are both public and are not decorated with keywords such as public,private in other languages. To define a private variable in Python you only need to add "__" two underscores to the variable name or function name. Internally, Python uses a name mangling technique to replace __membername with _classname__membername, so you'll be prompted to not find it when you use the name of the original private member externally. Like what:
Copy Code code as follows:
Class Person:
def __init__ (self):
Self.__name = ' haha ' #私有属性
Self.age = 22
def __get_name (self): # #私有方法
Return Self.__name
def get_age (self):
Return Self.age
person = person ()
Print Person.get_age ()
Print Person.__get_name ()
The result is: Traceback (most recent call last): File "E:\pythoner\zenghe\jay.py", line, in print person.__get_name () Attrib Uteerror:person instance has no attribute ' __get_name '
The __name we define here are private properties, and __get_name () is a private method. If you visit directly, you will be prompted not to find the relevant properties or methods, but if you really want to access private related data, it is also accessible, strictly speaking, private methods outside their class is accessible, but not easy to handle. Nothing in Python is truly private; internally, the names of private methods and properties are suddenly changed and restored so that they appear unusable with their given names.
I hope this article will help you with your Python programming.