티스토리 뷰

반응형

인스턴스 변수

python이 아닌 다른 프로그래밍 언어를 사용하면 클래수 변수를 선언할 때 protected, private를 사용하는 것에 익숙할 것이다. 하지만 python은 명시적으로 인스턴스의 보호 범위를 지정해주는 키워드가 없다. 대신 그렇게 사용하겠다는 변수의 이름을 규칙으로 정하여 사용한다.

public 변수

일반적으로 사용하는 클래스의 변수는 모두 publice 변수로 어디서든 접근이 가능하다.

class Student:
    def __init__(self, name):
        self.name = name

student = Student('철수')
print(student.name)
# 철수

protected 변수

변수 앞에 _ 를 붙여주면 protected 변수가 된다. 다만 이는 그렇게 사용하겠다는 약속일 뿐이고 강제성은 없다. 따라서 _를 붙인 변수를 만들더라도 접근이 가능하다.

class Student:
    def __init__(self, name):
        self._name = name

student = Student('철수')
print(student._name)
# 철수

다만 ide에 따라서 protected 변수에 접근한다는 메시지를 밑줄로 알려준다.(아래는 pycharm)

private 변수

  • 아래와 같이 변수 앞에 _기호를 두 개 붙여서 private 변수로 만들어 줄 수 있다.
  • 인스턴스를 생성해서 해당 변수를 접근하려고 하면 에러가 난다.
class Student:
    def __init__(self, name):
        self.__name = name

student = Student('철수')
print(student.__name)
# AttributeError: 'Student' object has no attribute '__name'
  • 다만 완전히 강제성이 있는 것은 아니라 private 변수를 어떻게든 찾으려면 접근할 수 있다.
  • dir 함수를 사용하면 해당 인스턴스의 클래스 정보를 알 수 있다. 첫번째 항목을 보면 _Student__name이 있다. 이걸로 __name 변수에 접근할 수 있다.
  • 위처럼 private 변수는 _className__variableName 형식으로 접근이 가능하지만 되도록 getter, setter를 통해 접근하는게 코드를 이해하는데 도움이 된다.
dir(student)

"""
['_Student__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__'
"""
print(student._Student__name)
# 철수

정리

접근 제어자문법의미
Publicvariable외부로부터 모든 접근 허용
Protected_variable자기 클래스 내부 혹은 상속받은 자식 클래스에서만 접근 허용
Private__variable자기 클래스 내부의 메서드에서만 접근 허용

참고자료

[1] https://inkkim.github.io/python/파이썬-접근-제어자에-대하여/


Uploaded by N2T

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday