

super.함수명() 또는 부모클래스명.함수명()을 사용해 부모클래스의 함수 호출class 자식클래스명(부모클래스명):
super().__init__([부모클래스의 속성값])
[변수명]
def 함수명(self, 인자1, 인자2, ..):
[코드블록]
class Animal:
def sound(self):
return "동물이 소리를 낸다"
class Dog(Animal):
pass
class Cat(Animal):
def sound(self):
return "야옹"
dog = Dog()
cat = Cat()
dog.sound(), cat.sound()
import math
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
# def display(self):
# print(f"The area of the {self.shape} is {self.area()}.")
class Circle(Shape):
def __init__(self, r):
super().__init__("circle")
self.r = r
def area(self):
return math.pi * (self.r**2)
# def display(self):
# print(f"The area of the {self.shape} is {self.area()}.")
class Triangle(Shape):
def __init__(self, width, height):
super().__init__("triangle")
self.width = width
self.height = height
def area(self):
return (self.width * self.height)/2
# def display(self):
# super().display()
# print(f"The area of the {self.shape} is {self.area()}.")
shapes = [Rectangle(5, 10), Circle(7), Triangle(5,8)]
for shape in shapes:
shape.display()
print("Area:", shape.area())
Person의 속성 : name(이름), job_title(직업)Teacher의 추가 속성 : subject(과목)Student의 추가 속성 : grade(학년)display()메소드를 오버라이드하여 직업에 따라 다음과 같이 출력해보자.class Person:
def __init__(self, name, job_title='job seeker'):
self.name = name
self.job_title = job_title
def display(self):
print(f"My name is {self.name} and I am a {self.job_title}.")
class Teacher(Person):
def __init__(self, name, subject):
# super().__init__(name, "teacher")
super().__init__(name)
self.job_title = "teacher"
self.subject = subject
def display(self):
print(f"My name is {self.name} and I am a {self.job_title} of {self.subject}")
class Student(Teacher):
def __init__(self, name, subject, grade):
super().__init__(name, subject)
self.job_title = "student"
self.grade = grade
def display(self):
print(f"My name is {self.name} and I am a {self.job_title} studying {self.subject} in {self.grade}.")
s1 = Student("Lee", "math", 3)
s1.display()
t1 = Teacher("Kim", "math")
t1.display()
p1 = Person("Park")
p1.display()


try:
예외 발생 가능한 실행문
except:
예외 종류에 상관없이 발생만 하면 except 블록 실행문
except 예외:
예외 발생시 실행할 명령문
except (예외1, 예외2):
예외 발생시 실행힐 명령문
except 예외 as e:
예외 발생시 실행할 명령문과 오류 메시지 내용 확인
else:
예외가 발생하지 않을 경우 실행할 명령문
finally:
예외 발생 여부와 상관없이 실행할 명령문(주로 리소스 반납)
class OperException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return "error message : {}".format(self.msg)
def printGugudan(dan):
if dan < 2 or dan > 9:
raise OperException("2~9단만 가능")
for i in range(1,10):
print("{} * {} = {}".format(dan, i, dan*i))
try:
print("구구단 시작")
printGugudan(1)
print("구구단 끝")
except OperException as e:
print("구구단 오류", e)
num1, num2, operationdef calculator(num1, num2, operation):
try:
if not isinstance(num1, (int,float)) or not isinstance(num2, (int,float)):
raise TypeError("숫자를 입력해주세요.")
if operation == "+":
result = num1+num2
elif operation == "-":
result = num1-num2
elif operation == "*":
result = num1*num2
elif operation == "/":
if num2 ==0:
raise ZeroDivisionError("0으로 나눌 수 없습니다.")
else:
result = num1/num2
else:
raise ValueError("해당 연산자는 계산할 수 없습니다.")
except TypeError as te:
print("Error :", te)
except ZeroDivisionError as ze:
print('Error:', ze)
except ValueError as ve:
print('Error:', ve)
else:
print("계산 결과 =", result)
finally:
print("계산기를 종료합니다.")
calculator(10, 2, "+") # 정상 입력
calculator(10, "a", "+") # TypeError: num2가 숫자가 아님
calculator(10, 0, "/") # ZeroDivisionError: 0으로 나누기
calculator(10, 2, "^") # ValueError : operation이 사칙연산자가 아님
print()나머지연산자(%)를 이용한 형식 및 위치지정
r = 3
PI = 3.14159265358979
print("반지름: %d, 원주율: %f" % (r, PI)) # 지정된 위치에 데이터 출력
print("반지름: %d, 원주율: %.2f" % (r, PI)) #소수점 2자리까지 출력
print("{0}, {1},{2},...{n}".format(data0, data1, data2,...datan))animal_0 = "cat"
animal_1 = "dog"
animal_2 = "fox"
print("Animal: {0}".format(animal_0))
print("Animal: {0},{1},{2}".format(animal_0, animal_1, animal_2))

data = input("문자열")# 정사각형의 변의 길이를 입력받아 넓이를 구하는 예제
a = input("정사각형 한 변의 길이는?: (정수로 입력)")
area = int(a) ** 2 # 입력데이터를 'int'로 변환하여 계산
print("정사각형의 넓이: {}".format(area))
# 숫자형의 입력의 경우, 입력되는 숫자가 정수인지 실수인지 모를때 `float()`를 이용
b = float(input("정사각형 한 변의 길이는?: (숫자로 입력하세요)"))
area = b ** 2 # 입력데이터를 'float'로 변환하여 계산
print("정사각형의 넓이: {}".format(area))