Python's private property and "protected" property

From "fluent Python"

Python can not be used like Java private modifiers to create private property, but Python has a simple mechanism to avoid accidentally overwriting "private" property subclass.

for example. There is a Dog class, this class uses the internal mood instance property, but did not open it. Now, you create a subclass Dog: Beagle. If you have no knowledge of the case and creates an instance property named mood, then the method will be inherited in the mood of the class attribute Dog overwritten.

To avoid this situation, if __mood form (two leading underscores, no or at most a trailing underscore) named instance attribute, Python will __dict__ attribute name stored in the attribute instance, and will preface an underscore and class name. Thus, for Dog class, it will become __ Mood _Dog__mood; in Beagle class, it becomes _Beagle__mood. This language feature called Name rewrite (name mangling).

>>> v1 = Vector2d(3, 4)
>>> v1.__dict__
{'_Vector2d__y': 4.0, '_Vector2d__x': 3.0}
>>> v1._Vector2d__x
3.0

Name rewrite is a security measure, we can not guarantee foolproof: It is intended to prevent accidental access. Just know rewriting mechanism of private property name, anyone can directly read private property - which is actually useful for debugging and serialization. In addition, as long as v1._Vector__x = 7 write this code, you can easily direct assignment for the private component Vector2d instance.

Some corners of the Python documentation of the use of an underscore prefix tag attributes are called "protected" property. Use this form self._x property protection practices are common. Python interpreter will not do for the property name with a single underscore the special treatment, but this is a lot of Python programmers strictly comply with the agreement, they would not access such properties outside the class.

Original articles published 0 · won praise 0 · Views 148

Guess you like

Origin blog.csdn.net/Airfrozen/article/details/104354596