
[참조]https://dojang.io/mod/page/view.php?id=2384
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self): # 메서드 재사용
print(f'반갑습니다. {self.name}입니다.')
class Professor(Person):
def __init__(self, name, age, department):
self.name = name
self.age = age
self.department = department
class Student(Person):
def __init__(self, name, age, gpa):
self.name = name
self.age = age
self.gpa = gpa
p1 = Professor('박교수', 49, '컴퓨터공학과')
s1 = Student('김학생', 20, 3.5)
# 부모 Person 클래스의 talk 메서드를 활용
p1.talk() # 반갑습니다. 박교수입니다.
# 부모 Person 클래스의 talk 메서드를 활용
s1.talk() # 반갑습니다. 김학생입니다.
사용 전
class Person:
def __init__(self, name, age, number, email):
self.name = name
self.age = age
self.number = number
self.email = email
class Student(Person):
def __init__(self, name, age, number, email, student_id):
self.name = name
self.age = age
self.number = number
self.email = email
self.student_id = student_id
```
사용 후
class Person:
def __init__(self, name, age, number, email):
self.name = name
self.age = age
self.number = number
self.email = email
class Student(Person):
def __init__(self, name, age, number, email, student_id):
# 부모클래스의 init 메서드 호출
super().__init__(name, age, number, email)
self.student_id = student_id
```
# super 사용 예시 - 1
class ParentA:
def __init__(self):
self.value_a = 'ParentA'
def show_value(self):
print(f'Value from ParentA: {self.value_a}')
class ParentB:
def __init__(self):
self.value_b = 'ParentB'
def show_value(self):
print(f'Value from ParentB: {self.value_b}')
class Child(ParentA, ParentB):
def __init__(self):
super().__init__() # ParentA 클래스의 __init__ 메서드 호출
self.value_c = 'Child'
def show_value(self):
super().show_value() # ParentA 클래스의 show_value 메서드 호출
print(f'Value from Child: {self.value_c}')
child = Child()
child.show_value()
# Value from ParentA: ParentA
# Value from Child: Child
# super 사용 예시 - 2
class A:
def __init__(self):
print('A Constructor')
class B(A):
def __init__(self):
super().__init__()
print('B Constructor')
class C(A):
def __init__(self):
super().__init__()
print('C Constructor')
class D(B, C):
def __init__(self):
super().__init__()
print('D Constructor')
obj = D()
print(D.mro())
# A Constructor
# C Constructor
# B Constructor
# D Constructor
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
while # SyntaxError : invalid syntax
5 = 3 # SyntaxError : cannot assign to literal
print('hello # SyntaxError : EOL while scanning string literal
print( # SyntaxError : unexpceted EOF while parsing
try :
# 예외가 발생할 수 있는 코드
except : 예외
# 예외 처리 코드
try:
num = int(input('100으로 나눌 값을 입력하시오 : '))
print(100 / num)
except (ValueError, ZeroDivisionError):
print('제대로 입력해주세요.')
my_list = []
try:
number = my_list[1]
except IndexError as error:
print(f'{error}가 발생했습니다.')
# list index out of range가 발생했습니다.
| EAFP | LBYL |
|---|---|
| "일단 실행하고 예외를 처리" | "실행하기 전에 조건을 검사 |
| 코드를 실행하고 예외가 발생하면 예외처리를 수행 | 코드 실행전에 조건문 등을 사용하여 예외 상황을 미리 검사하고, 예외 상황을 피하는 방식 |
| 코드에서 예외가 발생할 수 있는 부분을 미리 예측하여 대비하는 것이 아니라, 예외가 발생한 후에 예외를 처리 | 코드가 좀 더 예측 가능한 동작을 하지만, 코드가 더 길고 복잡해질 수 있음 |
| 예외 상황을 예측하기 어려운 경우에 유용 | 예외 상황을 미리 방지하고 싶을 때 유용 |