Python “protected” attributes

后端 未结 7 1323
迷失自我
迷失自我 2020-12-13 03:39

How do I access a private attribute of a parent class from a subclass (without making it public)?

相关标签:
7条回答
  • 2020-12-13 04:44

    if the variable name is "__secret" and the class name is "MyClass" you can access it like this on an instance named "var"

    var._MyClass__secret

    The convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10

    Of course, anybody can modify it if it really wants.

    0 讨论(0)
提交回复
热议问题