SoFunction
Updated on 2025-03-04

Let's talk about the underscore "_" in Python in detail

Preface

If you just take a copy of Python code, you can almost see many "_" figures.

In Python, underscore(_) has a variety of uses and meanings, depending on where they are and how they are used. Here are all listed for comparison and viewing:

1. __xxx__ (before and after double underscore)

This form is often used for special methods and attributes, also known as "magic methods" or "double underscore methods". These methods and properties are built in Python and have special meanings and uses. For example:

  • __init__: The initialization method of the class.
  • __str__: Returns the string representation of the object.
  • __len__: Returns the length of the object.
  • __add__: Defines the addition behavior of an object.
class MyClass: 
    def __init__(self, value): 
         = value 
    def __str__(self): 
        return f"MyClass with value {}" 

obj = MyClass(10) 
print(obj) 
# Output: MyClass with value 10

2. _xxx (single underscore prefix)

Single underscore prefixes are usually used to represent internal variables or methods, prompting developers that these variables or methods are part of the internal implementation and should not be directly accessed or modified. This is a naming convention and does not really restrict access.

class MyClass:
    def __init__(self, value):
        self._internal_value = value

    def get_value(self):
        return self._internal_value

obj = MyClass(10)
print(obj._internal_value)  # Output: 10

3. xxx_ (single underscore suffix)

Single underscore suffixes are often used to avoid conflicts with Python keywords. For example, if you have a variable name that conflicts with Python keywords, you can use a single underscore suffix to avoid conflicts.

class_ = "MyClass"
print(class_) 
# Output: MyClass

4. __xxx (double underscore prefix)

Double underscore prefix will trigger name mangling and modify the variable or method name to_ClassName__xxx, to avoid subclasses accidentally overwriting private variables or methods of parent class. This approach provides a weak "private" mechanism.

class MyClass:
    def __init__(self, value):
        self.__private_value = value

    def get_value(self):
        return self.__private_value

obj = MyClass(10)
print(obj._MyClass__private_value)  # Output: 10

5. _(Single underline)

Single underscores are often used as placeholders for temporary variables or ignore variables. For example, loop variables are ignored in a loop, or some values ​​are ignored when unpacking.

for _ in range(5): 
    print("Hello") 

a, _, c = (1, 2, 3) 
print(a, c) # Output: 1 3

6. __ (double underscore)

Double underscores are not usually used alone, but may appear in special methods or attributes in some cases. For example,__all__A common interface used to define a module.

__all__ = ["MyClass", "my_function"]

7. _xxx_ (before and after single underscore)

This form is often uncommon, but is sometimes used to represent internal variables or methods, similar to a single underscore prefix.

class MyClass:
     def __init__(self, value): 
        self._value_ = value 
    def get_value(self): 
        return self._value_ 

obj = MyClass(10) 
print(obj._value_) # Output: 10

Summarize

  • __xxx__: Special methods and properties.
  • _xxx: Internal variable or method.
  • xxx_: Avoid conflicts with Python keywords.
  • __xxx: Name modification, providing a weak "private" mechanism.
  • _: Temporary variable or placeholder for ignore variables.
  • __: Usually not used alone, but may appear in special methods or attributes.
  • _xxx_: Internal variable or method, similar to single underscore prefix.

By the way, other common symbols other than operators:

# Commentsa = [1, 2, 3]  # Listb = (1, 2, 3)  # Tuplec = {1, 2, 3}  # gatherd = {'a': 1, 'b': 2}  # dictionary
# Function calldef my_function(x):
    return x + 1

print(my_function(5))  # Output: 6
# Sliceprint(a[1:3])  # Output: [2, 3]
# Collection Operatione = {3, 4, 5}
print(c | e)  # Output: {1, 2, 3, 4, 5}print(c & e)  # Output: {3}print(c - e)  # Output: {1, 2}print(c ^ e)  # Output: {1, 2, 4, 5}
  • #: Comments
  • \: Continuing the line character
  • @: Decorators
  • :: used for slices, dictionary key-value pairs, function definitions, class definitions, etc.
  • .: Attribute access
  • ,: Tuple and parameter separator
  • ;: Statement separator (usually not recommended)
  • (): Tuple, function call, priority
  • []: List, Index, Slice
  • {}: Dictionary, collection
  • |: Collections and union
  • &: Collection and intersection
  • -: Set difference set
  • ^: Set symmetric difference set

This is all about underscores in Python. For more information about underscores related to Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!