1. 학습목표

2. 학습내용
# class structure
# 파이썬 클래스 특별 메소드 심화 활용 및 상속
# Class ABC
# 추상클래스
# class 선언
class VectorP(object):
def __init__(self, x, y):
## 언더스코어 2개(__)는 private 변수 선언방법!
self.__x = float(x)
self.__y = float(y)
def __iter__(self):
return (i for i in (self.__x, self.__y)) # Generator
# getter/setter 만들기! getter를 먼저 만들고 나서 setter를 만들어야 한다!
# getter
@property
def x(self): # 함수의 네이밍은 보통 변수명으로!
print('Called Property X')
return self.__x
@x.setter # setter는 "변수명.setter"의 형태로 데코레이터를 표시합니다!
def x(self, v):
print('Called Property X Setter')
self.__x = float(v)
@property
def y(self): # 함수의 네이밍은 보통 변수명으로!
print('Called Property Y')
return self.__y
@y.setter # setter는 "변수명.setter"의 형태로 데코레이터를 표시합니다!
def y(self, v):
print('Called Property Y Setter')
if v < 30:
raise ValueError('30 Below is not possible.')
self.__y = float(v)
# 객체 선언
v = VectorP(20, 40)
# 밑줄이 2개인 인스턴스 변수는(예: .__x)! 파이썬에서 직접 접근이 불가능하게 되어 있다!
# 밑줄이 1개인 인스턴스 변수(._x)는 직접접근 가능!
# print('EX1-1', v.__x, v.__y)
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 21, in <module>
print('EX1-1', v.__x, v.__y)
AttributeError: 'VectorP' object has no attribute '__x'
"""
# __inter__ 메소드 확인
for val in v:
# print('EX1-2 -', val)
pass
"""
EX1-2 - 20.0
EX1-2 - 40.0
"""
# Getter, Setter
# print(v.__x)
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 47, in <module>
print(v.__x)
AttributeError: 'VectorP' object has no attribute '__x'
"""
# 클래스 내부에 "def x"(getter)를 정의하였기 때문에 가능!
# print(v.x)
"""
Called Property X
20.0
"""
# 클래스 내부에 "def x"(setter)를 정의하였기 때문에 가능!
# v.x = 10
"""
Called Property x
20.0
"""
# v.y = 20
"""
Called Property Y Setter
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 90, in <module>
v.y = 20
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 39, in y
raise ValueError('30 Below is not possible.')
ValueError: 30 Below is not possible.
"""
# print('EX1-2', dir(v))
"""
EX1-2 ['_VectorP__x', '_VectorP__y',
'__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'x', 'y']
"""
# print('EX1-2', v.__dict__)
"""
EX1-2 {'_VectorP__x': 20.0, '_VectorP__y': 40.0}
"""
# print('EX1-3 -', v.x, v.y)
"""
Called Property X
Called Property Y
EX1-3 - 20.0 40.0
"""
3. 느낀 점