All about

In Python, the use of _ (single underscore) and __ (double underscore) has special meanings in terms of naming conventions.

 

_ (Single Underscore):

A single underscore is commonly used as a variable name when you want to ignore values, especially in unpacking or loops.

It is often used to signal to other programmers that the value is intended to be ignored.

for _ in range(5):
    # The underscore is used to ignore the value during iteration.
    print("Hello")

 

__ (Double Underscore):

Double underscores are used for "name mangling" within a class to avoid naming conflicts.

If an attribute name in a class starts with __, Python will change the name to _classname__attribute to prevent collisions. This is useful for preventing name clashes in subclasses or external code.

class MyClass:
    def __init__(self):
        self.__my_private_attribute = 42

obj = MyClass()
# Actually stored as _MyClass__my_private_attribute
print(obj.__my_private_attribute)  # Raises an error

 

Double underscores are used as a mechanism to prevent name clashes, but in general, Python's philosophy emphasizes "explicit is better than implicit," so directly accessing attributes with a single underscore for name mangling is less common. Single underscore usage for avoiding name clashes is more prevalent.

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading