This article mainly introduces the usage of python private attributes and methods. The example analyzes the principles and usage skills of python private attributes and methods, which has some reference value, for more information about python private attributes and methods, see the examples in this article. Share it with you for your reference. The specific implementation method is as follows:
Python's default member functions and member variables are both public, and they are not modified by keywords such as public and private in other languages. To define a private variable in python, you only need to add two underscores before the variable name or function name, so this function or variable will be private. Internally, python uses name mangling technology to replace _ membername with _ classname _ membername. Therefore, when you use the name of the original private member externally, the system will prompt that the system cannot be found. For example:
The code is as follows:
Class Person:
Def _ init _ (self ):
Self. _ name = 'hahaha' # Private attributes
Self. age = 22
Def _ get_name (self): # Private method
Return self. _ name
Def get_age (self ):
Return self. age
Person = Person ()
Print person. get_age ()
Print person. _ get_name ()
Running result: 22 Traceback (most recent call last): File "E: \ pythoner \ zenghe \ jay. py ", line 38, in print person. _ get_name () AttributeError: Person instance has no attribute '_ get_name'
The _ name defined here is a private property, __get_name () is a private method. If you access the data directly, you will be prompted that you cannot find the relevant attributes or methods. However, if you really want to access private data, you can also access the data. Strictly speaking, private methods can be accessed outside their classes, but they are not easy to handle. There is nothing really private in Python; internally, the names of private methods and properties are suddenly changed and restored, so that they seem to be unusable with their given names
I hope this article will help you with Python programming.