예를 들어, 수강신청 프로그램을 작성한다.
수강신청 관련
- 주체들(교수, 학생, 관리자)
- 행동(수강신청, 과목입력)
- 데이터(수강과목, 강의 과목)
위와 같이 객체들을 나누어 프로그램 작성 후 연결하는 방법이 객체 지향 프로그램이라고 한다.
축구 선수 정보를 Class로 구현하기 👇🏻
class SoccerPlayer(object):
def __init__(self, name, position, back_number):
self.name = name
self.position = position
self.back_number = back_number
def change_back_number(self, new_number):
print("선수의 등번호를 변경합니다 : From %d to %d" % (self.back_number, new_number))
self.back_number = new_number
Python에서의 __의미
특수한 에약 함수나 변수 그리고 함수명 변경(맨글링)으로 사용
ex. __main__,__add__, __str__, __eq__
__str__ : print(class_name)
실행시 출력형태에 대한 예약어.
__add__ : class의 +
연산자에 대해 변경할수 있는 예약어.
self
를 추가해야만 class함수로 인정됨위 SoccerPlayer를 바탕으로 사용 시 👇🏻
jinhyun = SoccerPlayer("Jinhyun","MF",10)
print("현재 선수의 등번호는: ", jinhyun.back_number)
class Person(object): # 부모 클래스 Person 선언
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def about_me(self): # Method 선언
print("저의 이름은 ", self.name, "이구요, 제 나이는 ", str(self.age), "살 입니다.")
class Employee(Person): # 부모 클래스 Person으로 부터 상속
def __init__(self, name, age, gender, salary, hire_date):
super().__init__(name, age, gender) # 부모객체 사용
self.salary = salary
self.hire_date = hire_date # 속성값 추가
def do_work(self): # 새로운 메서드 추가
print("열심히 일을 합니다.")
def about_me(self): # 부모 클래스 함수 재정의
super().about_me() # 부모 클래스 함수 사용
print("제 급여는 ", self.salary, "원 이구요, 제 입사일은 ",self.hire_date," 입니다.")
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')]
for animal in animals:
print(animal.name + ': ' + animal.talk())
class Inventory(object):
def __init__(self):
self.__items = [] # __를 사용하여 Private 변수로 선언
def add_new_item(self, product):
if type(product) == Product:
self.__items.append(product)
print("new item added")
else:
raise ValueError("Invalid Item")
def get_number_of_items(self):
return len(self.__items)
class Inventory(object):
def __init__(self):
self.__items = []
@property #property decorator 숨겨진 변수를 반환하게 해줌 : print(my_inventory.items)
def items(self):
return self.__items
파이썬은 대부분의 라이브러리가 이미 다른 사용자에 의해서 구현되어 있다.
-> 남이만든 프로그램쓰는법 객체 < 모듈
import
와 __all__ keyword 사용강의 내용 중 decorator에 대한 논의를 시작으로 진행됨
해당 논의가 끝나고 팀원분들 중 웹 개발자로 현직에서 일하시다가 오신분들도
계셨어서, IT의 현직에서 일하셨던 분들에게 궁금했던 사항들을 몇개 여쭤볼수 있었다.