object: 상속 받는 부모 클래스. object 클래스는 python3에서 자동 상속되므로 생략 가능
cf. Python naming rule
snake_case (띄어쓰기 부분에 _ 사용) → 변수명 / 함수명의 작명 방식
CamelCase (단어의 첫 글자를 대문자로 작성) → Class명의 작명 방식
attribute 추가하기
cf. 파이썬에서 ‘__’의 의미
특수한 예약 함수 및 변수에 사용
ex. _main__, __init__ 등
함수명 변경(name mangling)시에 사용
def __str__(self): # str 함수를 새로 정의
return "Hello World~!"
method 구현하기
기존 함수를 정의하는 것과 비슷하나, parameter로 반드시 self를 추가해야 class의 method로 인정됨
self: 생성된 instance 자신
03 OOP characteristics
03-1 inheritance 상속
부모 클래스로부터 attribute와 method를 물려받은 자식 클래스를 생성하는 것
class Person(object): # 부모 클래스
def __init__(self, name, age):
self.name = name
self.age = age
class Korean(Person): # 자식 클래스
pass
first_Korean = Korean("jieun", 23)
print(first_Korean.name) # jieun
class Person(object): # 부모 클래스 Person 선언
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def about_me(self):
print("저의 이름은 ", self.name, "이구요, 제 나이는 ", str(self.age), "살입니다.")
class Employee(Person): # 자식 클래스 Employee 선언
def __init__(self, name, age, gender, salary, hire_date):
super().__init__(name, age, gender) # 부모 클래스의 attribute 상속
self.salary = salary
self.hire_date = hire_date
def do_work(self):
print("열심히 일을 합니다.")
def about_me(self): # 부모 클래스의 method 재정의
super().about_me() # 부모 클래스의 method 상속
print("제 급여는 ", self.salary, "원 이구요, 제 입사일은 ", self.hire_date," 입니다.")
first_employee = Employee("지은", "23", "여", "1000000", "2023/3/6")
first_employee.about_me()
03-2 polymorphism 다형성
같은 이름를 가진 메소드의 내부 로직을 다르게 작성
03-3 visibility 가시성
visibility 가시성
객체 정보의 공개 범위를 조절하는 것
누구나 객체 정보에 접근할 수 있다면, 객체의 사용자가 임의로 객체를 수정하거나 불필요한 정보가 제공되는 등의 문제가 발생할 수 있음
cf. encapsulation
캡슐화 또는 정보 은닉 (Information Hiding)
객체의 attribute와 method를 하나로 묶음 + 객체 구현 내용의 일부를 내부에 은닉
private attribute & property decorator
attribute 앞에 __를 붙여서 private attribute로 만듦
wallet method를 통해 private attribute인 wallet에 접근할 수 있도록 함
댓글