[python] class ; single underscore, double underscore

2025. 8. 17. 10:10python/python

When we are making some class, we often see the _ or __ in class.

But what do they mean?

Actually, _ means it is intended to be used inside the class, but it's not enforced.

__ means it is also intended to be used inside the class, but with stronger protection. In this case, __hidden naming triggers Name Mangling, so the __hidden is gonna change to _ClassName__hidden. 

 

class nn:
    def __init__(self):
        self._secret = 99 
    
# accessible 
ne = nn() 
ne._secret 

class nn1:
    def __init__(self):
        self.__secret = 99 

# not accessible(default)
ne1 = nn1() 
ne1._nn1__secret

'python > python' 카테고리의 다른 글

[Python] Module에대한 이해  (3) 2025.07.12