- Hands-On Penetration Testing with Python
- Furqan Khan
- 282字
- 2021-07-02 14:13:58
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.
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- HTML5+CSS3王者歸來
- Node.js 10實戰(zhàn)
- .NET 4.0面向?qū)ο缶幊搪劊夯A(chǔ)篇
- Vue.js 3.0源碼解析(微課視頻版)
- 新編Premiere Pro CC從入門到精通
- Android Native Development Kit Cookbook
- Learning Concurrent Programming in Scala
- Go語言編程
- Scratch·愛編程的藝術(shù)家
- 青少年學(xué)Python(第2冊)
- Practical Predictive Analytics
- Mudbox 2013 Cookbook
- 快樂編程:青少年思維訓(xùn)練
- Java 7 Concurrency Cookbook