Python private property and method instance analysis

  • 2020-04-02 14:28:22
  • OfStack

An example of this article examines python's private properties and methods. Share with you for your reference. The specific implementation method is as follows:

Python's default member functions and variables are all public, and are not decorated with keywords like public or private in other languages. To define a private variable in python, you simply need to put "__" before the name of the variable or function, and the function or variable will be private. Internally, python USES a name mangling technique to replace the _classname_membername with the _classname_membername, so when you use the name of the original private member externally, you will be prompted that it cannot be found. Such as:

class Person:
   def __init__(self):
       self.__name = 'haha'# Private property
       self.age = 22    def __get_name(self):## Private methods
       return self.__name    def get_age(self):
       return self.age person = Person()
print person.get_age()
print person.__get_name()

The result is: 22 Traceback (most recent call last): File "E:\pythoner\zenghe\ ja. py", line 38, in print person. s.

The _name we define here is a private property, and the _name() is a private method. If you access it directly, you'll be told that you can't find the relevant properties or methods, but if you really want to access private data, you can. Strictly speaking, private methods are accessible outside their classes, but not easily. Nothing is truly private in Python; 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 has helped you with your Python programming.


Related articles: