하나의 클래스라는 단위 안에 변수로 표현되는 데이터와 이 데이터를 핸들링하는 함수로 구성되어 있어요.
데이터와 로직이 하나의 단위로 묶여있어요 - 인캡슐레이션(Encapsulation)
메소드는 해당 데이터의 상태들을 제어하는 역할
self에 객체의 주솟값이 들어가서 원하는 필드들을 제어
class Student(object):
def __init__(self, name, dept):
self.name = name
self.dept = dept
def get_student_info(self):
print(self.name, self.dept)
stu1 = Student('홍길동','CS')
print(stu1.name) #property(변수)를 제어
stu1.name = '최길동' # property를 변경 (객체지향 측면에서는 바람직하지 않아요. 보안에 취약)
stu1.get_student_info() # method를 호출
홍길동
최길동 CS
이쯤에서 내장함수를 하나 더 알아보아요!
# dir() : 객체가 가지고 있는 property와 method를 알려줘요!
print(dir(stu1))
홍길동 최길동 CS ['__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__', 'dept', 'get_student_info', 'name']
리스트 안에 문자의 형태로 어떤 이름의 method 와 property 가 있는지 알려주는 함수.
//
pyrhon은 객체지향 면에서 잘 맞지 않는 부분들도 가지고 있어요.
class Student(object):
def __init__(self, name, dept):
self.name = name
self.dept = dept
def get_student_info(self):
print(self.name, self.dept)
def set_stu_name(self,name):
self.name = name
stu1 = Student('홍길동','CS')
# 당연히 존재하는 property 와 method만 이용할 수 있어요!
stua1.address = ' 서울' #객체지향 관점에서 봤을 때는 당연히 오류, 허용하면 안 돼요
#프로그래밍의 유연성을 제공하기 위해 동적(변함) property
# method를 허용
print(stu1.address)
서울
//
__init__ : 객체가 생성될 때 자동으로 호출되고 instance를 self라는 인자로 받아서
일반적으로 property를 초기화할 때 사용돼요! →다른 언어의 constructor (생성자)의 역할을 해요!
python에서는 초기화 시켜주는 놈 initializer라고 불러요!
class 내부에 property 와 method가 존재하게 되는데 크게
instance variable 과 class variable (둘다 property)
첫번째 인자에 self. 이 붙어있으면 거의 대부분 instance variable
ex) self.name
class variable defs는 메서드 내에 있지 않아요.
ex)
class Student(object):
schoalship_rate = 3.5 # class variable, property
def __init__(self, name, dept): #self.name : property, instance variable
self.name = name
self.dept = dept
def get_student_info(self): # method, instance method
print(self.name, self.dept)
def set_stu_name(self, name):
self.name = name
stu1 = Student('홍길동','CS')
##
magic method
→ method 이름 앞에 __ 가 붙은 method ex)__iniit__ #메소드를 알려주는 print(dir()) 하면
magic method 많이 볼 수 있어요!
__str__ instance 를 문자열화 시킬때 호출되는 magic method
#####
class Car(object):
def __init__(self, maker, cc):
self.maker = maker
self.cc = cc
def __lt__(self,other): # __lt__ = lessthan = <
if self.cc < other.cc:
return '{}의 배기량이 작습니다.'.format(self.maker)
else:
return '{}의 배기량이 작습니다.'.format(other.maker)
car_1 = Car('현대', 3000)
car_2 = Car('기아', 2000)
print(car_1 < car_2) #print(car_1.cc< car_2.cc)
기아의 배기량이 작습니다.
'Python' 카테고리의 다른 글
0707 python 상속 (0) | 2021.07.07 |
---|---|
0707 python class (0) | 2021.07.07 |
0702 class 2 (0) | 2021.07.02 |
0702 class (0) | 2021.07.02 |
0702 절차적 프로그래밍, 구조적 프로그래밍, 함수 지향적 프로그래밍 (0) | 2021.07.02 |
댓글