Python 접근제한자 public, protected, private

접근제한자는 어떤 클래스의 변수, 인스턴스 변수 , 메서드 사용을 제한한다.

python 에는 public, protected, private이 있다.

java에는 public, protected, private, default가 있다.


public

외부 환경이 클래스의 멤버에 접근 가능하다.

(var)


protected

자신 클래스 내부 or 상속받은 자식 클래스에서  접근 가능하다.

_ 언더바 1개 ( _var )


private

자신 클래스 내부에서만 접근가능하다.

__ 언더바 2개 (__var)



파이썬에서 접근제한은 변수나 메서드 이름을

mangling하여 저장함으로서 접근 제한 구현을 하고있기 때문에

엄밀하게 제한이 된 것은 아니며

파이썬 인터프리터에서 접근제한자 오용 오류를 띄우지는 않는다.

IDE에 따라 경고 메시지를 띄워주는 경우는 있다.


class Student:
    __homeschool = "j_School"  # private class attribute
    __teacher = "Andrew Drake"  # private class attribute

    def __init__(self, name, age):  # instance attribute
        self.name = name  # instance public attribute
        self.__age = age  # instance private attribute

    # def __ display(self):  # private method
    #    print("This is private method")


class ChildStudent(Student):
    __another_school = "b_School"
    __teacher = "MJ"

std = Student("Kim Seung Joo", 20)
print(std.name)
# print(std.age)
print(dir(std))

# std.__homeschool
# AttributeError: 'Student' object has no attribute '__homeschool'

cstd = ChildStudent("Kim Sung Joo", 29)

print(dir(cstd))

Kim Seung Joo
['_Student__age', '_Student__homeschool', '_Student__teacher', '__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__', 'name']
['_ChildStudent__another_school', '_ChildStudent__teacher', '_Student__age', '_Student__homeschool', '_Student__teacher', '__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__', 'name']
['__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__', 'age', 'gender']


출력 결과를 보면 mangling된 프로퍼티나 메서드들을 열람할 수 있다.

댓글

이 블로그의 인기 게시물

실무진 면접 경험으로 정리하는 백엔드 (1) : 에듀 테크 기업 면접

노마드코더 개발자북클럽 Clean code TIL 6 : 6장. 객체와 자료구조

백엔드 개발자가 Djnago fullstack 사이드 프로젝트를하며 ( html, css, vanillaJS 그리고 JS프레임워크 )