python/python
[python] class ; single underscore, double underscore
rudgh99_algo
2025. 8. 17. 10:10
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