Protected methods in Python



  • I understand Python, protected declared by one _ First, a private Two-- __♪ I don't understand why the Piton drives. protected meaning, it should only be available in its own class, right?

    class Make():
        _foo = "Protect <--";
    
    def fun():
       pass
    

    class MakeTwo(Make):

    def off(self):
       print(self._foo);
    

    t = Make();
    print t._foo; # Protect <--



  • The thing is, Python has no private or protected fields in classrooms. The use of the sign only informs users of the code that it is not worth using the field outside the class, but there is still access.

    It should be considered an implementation detail and subject to change without notice.

    So-called private fields are actually available outside the class, too. If the name of the field is used A.__fieldIf we have a copy of this class aTo this field __field May be consulted as follows: a._A__field

    https://docs.python.org/3/tutorial/classes.html#private-variables


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2