Python private attributes and Method Instance analysis, python private instance analysis
This article analyzes python's private attributes and methods. 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 the underscore "_" before the variable name or function name. Then the 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:
Copy codeThe 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.