public,private
- public 은 내부,외부에서 접근이 가능하다.(클래스 외부,클래스 내부)
class Public:
def __init__(self, name):
self.name = name
public1 = Public("seoul")
print(public1.name)
seoul
- private은 내부에서만 접근이 가능하다.(클래스 내부)
class Public:
def __init__(self, name):
self.__name = name
print(self.__name)
public1 = Public("seoul")
print(public1.__name)
seoul
Traceback (most recent call last):
File "C:\SSAFY\python\encapsulation.py", line 55, in <module>
print(public1.__name)
AttributeError: 'Public' object has no attribute '__name'
getter,setter
class Public:
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
public1 = Public("seoul")
print(public1.get_name())
public1.set_name("daejeon")
print(public1.get_name())
seoul
daejeon
property
- getter, setter를 간단하게 구현할 수 있게하는 데코레이터함수
class Public:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
self.__name = new_name
public1 = Public("seoul")
print(public1.name)
public1.name = "daejeon"
print(public1.name)
seoul
daejeon
데이터은닉의 장점
- 변수의 값을 사용해서 추가적인 후처리(문자열 붙이기 등)를 거친 후 보낼수 있다.
- 들어오는 인자들을 검증하며 코드를 수행할 수 있다.
class Public:
def __init__(self, name):
self.__name = name
@property
def name(self):
return "i love " + self.__name
@name.setter
def name(self, new_name):
if len(new_name) == 0 or len(new_name) >= 10:
raise ValueError()
else:
self.__name = new_name
public1 = Public("seoul")
print(public1.name)
public1.name = "daejeonaadasdasd"
print(public1.name)
i love seoul
Traceback (most recent call last):
File "C:\SSAFY\python\encapsulation.py", line 66, in <module>
public1.name = "daejeonaadasdasd"
File "C:\SSAFY\python\encapsulation.py", line 59, in name
raise ValueError()
ValueError