Does Python have “private” variables in classes?

后端 未结 12 1851
不思量自难忘°
不思量自难忘° 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:29

    The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.

    Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variables was free-for-all. When one implementation became deprecated it took a lot longer to identify all code paths that used that function. When use of setters and getters was forced, a debug statement could easily be written to identify that the deprecated method had been called and the code path that calls it.

    When you are on a project where anyone can write an extension, notifying users about deprecated methods that are to disappear in a few releases hence is vital to keep module breakage at a minimum upon upgrades.

    So my answer is; if you and your colleagues maintain a simple code set then protecting class variables is not always necessary. If you are writing an extensible system then it becomes imperative when changes to the core is made that needs to be caught by all extensions using the code.

提交回复
热议问题