Introduction to Python private variables and private methods

Introduction to Python private variables and private methods

Regarding Python private variables and private methods, under normal circumstances, developers can add a single underscore (_) before the method or attribute name to indicate that the method or attribute is for internal use only, but this is just a convention and is not mandatory Do not allow external access. To truly achieve the "private" effect, you can add a double underscore (__) before the method or attribute name, and automatically rewrite the method or attribute name inside Python, so that it cannot be directly accessed from outside the class, but it can still be accessed through Add a single underscore and the class name in front of it to access.

Python private variables

In Python, private variables are variables that start with two underscores (__) in the class definition. These variables are considered private because they cannot be directly accessed from outside the class.

[Official description of Python private variables https://docs.python.org/zh-cn/3/tutorial/classes.html#private-variables

Python prefixes the names of attributes with double underscores, making them inaccessible outside the class with simple names. However, inside the class, these properties can be used like any other property, except that they need to be referred to by special names.

For example:

class MyClass:
    def __init__(self):
        self.__private_var = 42

    def get_private_var(self):
        return self.__private_var

my_object = MyClass()
print(my_object.get_private_var())  # 输出结果:42
#print(my_object.__private_var)      # 报错:AttributeError: 'MyClass' object has no attribute '__private_var'
print(my_object._MyClass__private_var)# 输出结果:42 ,可以这样访问私有变量,但是不建议

In the above code, we defined a class called MyClass and set a private variable __private_var in its constructor __init__(). Then, we define a method called get_private_var() that returns the value of the private variable __private_var.

When we create a new instance of MyClass and call the get_private_var() method, we can successfully get the value of the private variable and output it. However, when we try to directly access the private variable __private_var, Python throws an AttributeError exception, because the attribute is not public and cannot be directly accessed from outside the class.

It is important to note that in Python, private properties are not truly private. They can still be accessed by special names. Specifically, Python interprets the private variable name as a new variable name that includes the class name and the variable name, and is prefixed with a single underscore, such as _MyClass__private_var. While this approach allows access to private variables in some cases, it is strongly discouraged as it makes your code harder to understand and maintain.

Python private methods

In Python, you can use double underscores (__) to define "private" methods, which are only accessible inside the class. Specifically, the method names starting with double underscores will be renamed to the form of _ClassName__my_private_method by the Python interpreter, so they cannot be directly called externally.

For example:

class MyClass:
    def __init__(self):
        self.__my_private_var = 42

    def __my_private_method(self):
        print("This is a private method.")
        print(f"The value of my_private_var is {self.__my_private_var}.")

obj = MyClass()
# obj.__my_private_method()  # 报错:AttributeError: 'MyClass' object has no attribute '__my_private_method'
obj._MyClass__my_private_method()  # Output: This is a private method. The value of my_private_var is 42.

In this example, we define a class MyClass, and define a "private" method __my_private_method in it, which can only be accessed inside the class. We then create an object of MyClass and assign it to the variable obj, but attempting to call obj.__my_private_method() directly results in an AttributeError because the method is "private". Instead, we can call this method indirectly through the _MyClass__my_private_method() method.

Although it is possible to access "private" methods by special names in Python, this is not good programming style.

appendix

python/classes and instances - access restrictions https://www.codenong.com/cs106668667/

Detailed explanation of class definition, instantiation, encapsulation and private variables/methods in Python object-oriented programming https://www.jb51.net/article/157112.htm

Guess you like

Origin blog.csdn.net/cnds123/article/details/131152069