官术网_书友最值得收藏!

Access modifiers in Python

In Python, we don't have access modifiers in the same way as we do in Java and C++. There is a partial workaround however, which  can be used to indicate which variables are public, protected, and private. The word indicate is important here; Python doesn't prevent the usage of protected or private members, it just indicates which members are which. Let's take a look at an example. Create  a class called AccessSpecifiers.py:

The preceding example shows us how access specifiers can be used in Python. Any variable that would be simply declared within a class is public by default, as we declared self.public. Protected variables in Python are declared by prefixing them with an underscore (_)  as seen in line 5, self._protected. But it must be noted that this does not prevent anyone from using them, as can be seen at line 23, in which we are using a protected member outside of the class. Private members in Python are declared by prefixing them with double underscore (__), as can be seen at line 6, self.__private. Again, however, there is nothing to prevent this member from being used outside the class. The way to access them is a little different, however; for private members, a specific convention is followed if they are to be accessed outside the class: instance._<className><memberName>. This is called name mangling.

What we have learnt here about access modifiers in Python is that Python does have notations to denote public, private, and protected members of a class, but it doesn't have any way for the members to be used outside their scope, so it's merely for identification purposes.
主站蜘蛛池模板: 太保市| 舒城县| 武汉市| 城口县| 桂平市| 宁强县| 阿克苏市| 贵德县| 谢通门县| 浠水县| 博客| 四子王旗| 侯马市| 余庆县| 四子王旗| 靖江市| 桑植县| 昌乐县| 庐江县| 宜阳县| 安图县| 长沙市| 稷山县| 韩城市| 安宁市| 淄博市| 连江县| 垣曲县| 辉县市| 板桥市| 合肥市| 洛扎县| 左权县| 临沂市| 涟源市| 石河子市| 延边| 永济市| 临洮县| 错那县| 湘阴县|