[Python]Property — Underscore

언더스코어(UnderScore)를 어떻게 사용하는지 확인해보자.

"""
Python Property(1) -- Underscore
다양한 언더스코어 활용
파이썬 접근지정자 설명
"""

# 예1 : Underscore

# unpacking
x, _, y = (1, 2, 3)
print(x, _, y)
'''
1 2 3
'''

x, *_, b = (1, 2, 3, 4, 5)
print(x, b)
'''
1 5
'''

# 값을 무시함
for _ in range(10):
    pass

# 값을 무시함
for _, val in enumerate(range(10)):
    pass


# 예2 : 접근 지정자로 활용(단, 강제하지 않음, Naming Mangling)
# name : public
# _name : protected
# __name : private

# property 미사용
class SampleA:
    def __init__(self):
        self.x = 0
        self.__y = 0
        self._z = 0


a = SampleA()
a.x = 1

print(f'x : {a.x}')
# print(f'__y : {a.__y}')  # AttributeError: 'SampleA' object has no attribute '__y'
print(f'_z : {a._z}')
"""
x : 1
_z : 0
"""

print(dir(a))
"""
['_SampleA__y', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_z', 'x']
"""

# 아래와 같이 변경 가능하다.(권장하지 않음)
a._SampleA__y = 2
# print(f'a._SampleA__y = {a._SampleA__y}')


# 예3 : Getter, Setter 활용
class SampleB:
    def __init__(self):
        self.x = 0
        self.__y = 0

    def get_y(self):
        return self.__y

    def set_y(self, value):
        self.__y = value


b = SampleB()
b.x = 1
b.set_y(2)

print(f"b.x = {b.x}")
print(f"b.y = {b.get_y()}")
"""
b.x = 1
b.y = 2
"""

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다