Private functions / Variables enforcement in python

后端 未结 2 1544
悲&欢浪女
悲&欢浪女 2020-12-20 04:17

I see a lot of python code that does \"loose\" private variables / functions. They\'ll declare functions / variables with one underscore (eg. _foo) and then use it just in t

相关标签:
2条回答
  • 2020-12-20 04:59

    No. And that's the philosophy of python: Do not make the compiler/parser enforce privacy since developers who want to access private members have ways to do so anyway (reflection etc.). The idea is telling people Hey, this is not part of the public API. If you use it improperly, it could breaks things or kill your cat. I might also change the signature often since it's not part of the public API and I don't have to care about people using it

    And fyi, you can actually access double-underscore variables (same applies for methods) from outside using obj._ClassName__variableName. Besides that it's not encouraged to use double underscores except for mixin objects - you can never know if someone wants to subclass your class.

    0 讨论(0)
  • 2020-12-20 05:16

    In Python, there is no strict concept(like Java for example) of private methods. Even using double underscores is still accessible by doing _classname__method.

    In short, don't go against the grain, rather go with the Python philosophy in which private is a convention, not a force.

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