Home >Backend Development >Python Tutorial >How to type underline in python
Underscore in Python has a special meaning. Python uses underscores as variable prefixes and suffixes to specify special variables.
Underline in Python can be typed using the Shift minus key on the keyboard. The minus key is located between 0 and the plus key. . (Recommended learning: Python video tutorial)
In Python, the underscore also has access rights similar to private and protected. Let’s analyze it in detail below.
Python主要存在四种命名: (1)object #公用方法 (2)__object__ #内建方法,用户不要这样定义 (3)__object #全私有,全保护(private) (4)_object #半保护(protected)
Core style: Avoid starting variable names with an underscore.
Because the underscore has special meaning to the interpreter and is the symbol used by built-in identifiers, we recommend that programmers avoid using an underscore as the beginning of variable names.
Generally speaking, the variable name _xxx is regarded as "private" and cannot be used outside the module or class.
When the variable is private, it is a good habit to use _xxx to represent the variable. Because variable names __xxx__ have special meaning to Python, this naming style should be avoided for ordinary variables.
The member variables starting with "single underscore" are called protected variables, which means that only class objects and subclass objects themselves can access these variables;
The member variables starting with "double underscore" are private members. This means that only the class object itself can access this data, not even subclass objects.
Starting with a single underscore (_foo) represents class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported with "from xxx import *";
With double (__foo) starting with an underscore represents the private members of the class;
(__foo__) starting and ending with a double underscore represents a special identifier for special methods in Python, such as __init__() representing the constructor of the class.
Example:
class Foo(): def __init__(): ... def public_method(): print 'This is public method' def __fullprivate_method(): print 'This is fullprivate_method' def _halfprivate_method(): print 'This is halfprivate_method' f = Foo() f.public_method() # OK f.__fullprivate_method() # Error occur f._halfprivate_method() # OK f._Foo__fullprivate_method() # OK
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to type underline in python. For more information, please follow other related articles on the PHP Chinese website!