Examples of Python private functions
Examples of Python private functions
Like most languages, Python also has a private concept:
• Private functions cannot be called outside their modules
• Private class methods cannot be called outside their classes
• Private attributes cannot be accessed from outside their classes
Unlike most languages, a Python function, method, or attribute is private or public, depending on its name.
If a Python function, class method, or attribute name starts with two underscores (but not ends), it is private; all others are public.
Python does not have the concept of class method protection (it can only be used in their own classes and subclasses ). Class methods are either private (only available in their own classes) or public (available anywhere ).
In MP3FileInfo, there are two methods: __parse and _ setitem __. As we have discussed, __setitem _ is a proprietary method. Generally, you do not call it directly, but call it by using dictionary syntax on a class, but it is public, and if there is a really good reason, you can call it directly (or even from outside the fileinfo module ). However, __parse is private because it has two underscores before its name.
Note: Method Naming C onventions
In Python, all dedicated methods (like _ setitem _) and built-in properties (like _ doc _) follow a standard naming convention: both start and end are underlined. Do not name your own methods and attributes in this way; in the end, it will only confuse you (or others.
1. Try to call a private Method
>>> import fileinfo >>> m = fileinfo.MP3FileInfo() >>> m.__parse("/music/_singles/kairo.mp3") (1) Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'MP3FileInfo' instance has no attribute '__parse'
(1) If you try to call a private method, Python will trigger a misleading exception and claim that the method does not exist. Of course, it does exist, but it is private, so it is not usable outside the class. Strictly speaking, private methods can be accessed outside their classes, but they are not easy to handle. There is nothing really private in Python; internally, the names of private methods and properties are suddenly changed and restored, so that they seem to be unusable with their given names. You can use the _ parse method of the MP3FileInfo class by using the _ MP3FileInfo _ parse name. Knowing this method is interesting, you must never use it in real code.
Private methods are private for some reason, but like many other things in Python, their privatization is basically a habit, not forced.
I hope you can understand the usage of Python private functions through this article. If you have any questions, please leave a message or go to the community on this site to discuss it. Thank you for reading this article and hope to help you, thank you for your support!