Is there a private variable in Python's class?

Asked 2 years ago, Updated 2 years ago, 105 views

I'm using Java and learning Python by reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms

While reading about the class, Python found that just using it in the constructor creates variables without having to declare them separately.

As below :

class Simple:
    def __init__(self1, str):
        print("inside the simple constructor")
        self1.s = str
    def show(self1):
        print(self1.s)
    def showMsg (self, msg):
        print (msg + ':', self.show())

If this is true, then the variable ss of the object in the Simple class can just change outside of the class, as shown below.

if __name__ == "__main__":
    x = Simple("constructor argument")
    x.s = "test15" # this changes the value
    x.show()
    x.showMsg("A message")

I learned about the public/private/protected variables through Java, and sometimes I don't want to allow outside-class access to internal variables, so the existence of these keywords makes sense. Why doesn't Python need this concept?

private class python

2022-09-21 18:37

1 Answers

This is a cultural difference. Python does not write values to instances or variables of other classes. In Java, if you really want to do that, there's no way to stop him. After all, editing the source code of the class itself can produce the same effect. Python eliminates this security trick and encourages programmers to take responsibility. And it actually works.

If you want to use a private variable for any reason, you can copy the private variable by putting ___code> before the variable name according to PEP 8. Python names variables like __foo to make it difficult for variables to be exposed outside of the class. (Of course, it can also be pierced if you want, just like the protection of variables in Java.))

In a similar convention, the _ suffix is used to mean not to do so even if access to the variable is not blocked in principle. Therefore, it is a rule not to access variables of other classes such as _foo or _bar.


2022-09-21 18:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.