파이썬의 특징
다른 언어들과 다르게 파이썬 객체의 모든 프로퍼티 와 함수는 public이다.
즉 호출자가 객체의 속성을 호출하지 못하도록 할 방법이 없다.
그래서 주어진 밑줄 규칙
1. 밑줄로 시작하는 속성은 해당 객체에 대해 private을 의미하지만, 외부에서 호출하지 않기를 기대하는 것. 그러나 금지하는 것은 아니다.
class Connector:
def __init__(self, source):
self.source = source
self.__timeout = 60 #이게 위의 사례
conn = Connector("postgresql://localhost")
print(conn.source)
print(conn._timeout)
print(conn.__dict__)
>>> postgresql://localhost
>>> 60
>>> {'source': 'postgresql://localhost', '_timeout': 60}
여기서 _timeout은 외부객체와 관련이 없어, 호출되지 않기 권장되는 속성인데, print하면 호출이 된다.
class Connector:
def __init__(self, source):
self.source = source
self.__timeout = 60 #이게 위의 사례
conn = Connector("postgresql://localhost")
print(conn.source)
print(conn.__timeout)
print(conn.__dict__)
print(vars(conn))
print(conn._Connector__timeout)
>>> postgresql://localhost
>>> Traceback (most recent call last):
File "chapter2.py", line 53, in <module>
print(conn.__timeout)
>>> AttributeError: 'Connector' object has no attribute '__timeout'
>>> {'source': 'postgresql://localhost', '_Connector__timeout': 60}
>>> 60
보다 싶이 '_Connector__timeout이라는 속성이 만들어졌다. 이는 이름 충돌없이 클래스의 매서드를 오버라이드하기 위해 만들어졌다.