Does Python have “private” variables in classes?

后端 未结 12 1838
不思量自难忘°
不思量自难忘° 2020-11-21 23:06

I\'m coming from the Java world and reading Bruce Eckels\' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Py

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:55

    It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

    If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).

    By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.

提交回复
热议问题