20221206- 파이썬 (상속, 다중상속, 예외처리, open api,

공현지·2022년 12월 11일

파이썬

목록 보기
9/11

상속 🍔

inheritance03

class Person:
    def __init__(self, name, phone=None):
        self.name = name
        self.phone = phone
    def __str__(self):
        return '<Person %s %s>' % (self.name, self.phone)

class Employee(Person):  # 괄호 안에 쓰여진 클래스는 슈퍼클래스를 의미한다.
    def __init__(self, name, phone, position, salary):
        Person.__init__(self, name, phone)  # Person클래스의 생성자 호출
        self.position = position
        self.salary = salary

p1 = Person('신동호', 1498)
print("p1.name->", p1.name)

m1 = Employee('신성화', 5564, '대리', 200)
m2 = Employee('오태우', 8546, '과장', 300)
print("m1.name, m1.position->", m1.name, m1.position)  # 슈퍼클래스와 서브클래스의 멤버를 하나씩 출력한다.
print("m1->", m1)
print("m2.name, m2.position->", m2.name, m2.position)
print("m2->", m2)

inheritance03

class Animal:  # Animal에 있는 cry를 Dog의 cry가 override 함
    def cry(self):
        print('...')

class Dog(Animal):
    def cry(self):
        print('멍멍')

class Duck(Animal):
    def cry(self):
        print('꽥꽥')

class Fish(Animal):  # Fish는 cry가 없으므로 Animal의 내용을 그대로 사용                  # 오버라이드 안   하고 아무것도 안하는 빈껍데기 사용하고 싶을때 --> pass
    pass

# in 뒤에는 튜플 안에 객체 3개 존재 -> each의 객체 형이 동적으로 결정되므로 그때마다의 cry가 다르게 사용
for each in (Dog(), Duck(), Fish()):
    each.cry()

multiinheritance 다중상속

클래스의 다중 상속
2개 이상의 부모 클래스로 부터 상속 받는것을 의미함.

class Add:                          # 부모클래스
    def add(self, n1, n2):
        return n1 + n2

class Multiply:                     # 부모클래스
    def multiply(self, n1, n2):
        return n1 * n2

# 클래스의 다중상속 (Add, Multiply 클래스를 상속 받는다)
class Calculator(Add, Multiply):    # 자식클래스
    def sub(self, n1, n2):
        return n1 - n2

cal = Calculator()
print(cal.add(1, 2))                # 3이 출력됨
print(cal.multiply(3, 2))           # 6이 출력됨






house 🏚 상속+오버라이딩


class HousePark:      
    lastname = "Park "    #사람이름이 박이고
    def __init__(self, name):     #init을 받아서 풀네임을 만든다
        self.fullname=self.lastname+name
    def travel(self, where):
        print("%s %s 여행을 가네" % (self.fullname , where))
    def love(self, other):
        print("%s, %s 사랑 하네" % (self.fullname , other.fullname))
    def fight(self, other):
        print("%s, %s 전쟁 났네" % (self.fullname, other.fullname))
    def __add__(self, other):      #예약어 
         print("%s, %s 결혼 하네" % (self.fullname, other.fullname))
    def add3(self, a , b):
        k= a+b
        print("2덧셈 %d + %d  = %d 입니다" % ( a , b , k))
    def  __sub__(self, other):
        print("%s, %s 각방 쓰네" % (self.fullname , other.fullname))

class HouseKim(HousePark):     #상속받아서 사용함 
    lastname = "Kim "

    def travel(self, where, day):    #오버라이딩 받아서 사용 
        print("%s %s으로 여행 %d일 가네" % (self.fullname, where, day))

    def add3(self, a, b, c, d):  #오버라이딩 받아서 사용
        k = a + b + c + d
        print("4덧셈 %d + %d  +%d  + %d= %d 입니다" % (a, b, c, d, k))


pey = HousePark("GiSun") # HousePark pey = new HousePark("GiSun");
julet=HouseKim('Eve')
pey.travel("정동진")
julet.travel("정동진", 3)
pey.love(julet)
#add사용하는법 +를 사용해도 되고 밑줄 두개 사용해도 가능 
pey+julet         
pey.__add__(julet)
pey.add3(3,5)
julet.add3(3, 5, 7, 9)
pey.fight(julet)
#__sub__ 사용법 (__add___랑 같음)
pey-julet




예외처리

exception01


try:
    k = 0
    # print("1.0 / k ->", 1.0 / k)
    number = float('hello')
    print("number->", number)
except   ZeroDivisionError:
    print('zero division error!!!')
except   ValueError as e:
    print('Not a Number '+str(e))
                         #e.getmessage 랑 똑같음 






❌ try except 안적어주면 에라가남
(자바랑 비슷함)

❌ 두번째 주성문처리하면 valuererror 남
그럼 다시 예외처리 해주기

▶ 예외 시에 내가 설정해놓은 것 뜸

exception02

❌ 0을 돌리면 에러가뜸
range (1,5) 해줄수도있지만 0일때 예외처리를 넣어주면됨
🔽

def division():
    for n in range(0, 5):
        try:
            print("n->", n)
            print(" 10.0 / n ->", 10.0 / n)
        except ZeroDivisionError:
            msg = "ZeroDivisionError"
            print("msg->", msg)


division()



exception03


print ("-------------------------------------------------------------")
print ("-                예외 처리 방법                                                                                  --")
print ("- 5. except 뒤에 아무런 예외도 기술하지 않으면 모든 예외에 대해 처리                            --")
print ("-------------------------------------------------------------")

try:
    # spam()
    print (1.0 / 0.0)
except:
    print ('Error  except 뒤에 아무런 예외도 기술하지 않으면 모든 예외에 대해 처리' )


exception04

print("-------------------------------------------------------------")
print("-                예외 처리 방법                               --")
print("- 7. 파일에서 숫자를 읽어와서 읽은 숫자로 나누기를 하는 예제          --")
print("--------------------------------------------------------------")

import os
print("os.getcwd()->", os.getcwd())
filename = 't.txt'

try:
    f = open(filename, 'r')
except IOError:
    msg = "IOError"
    print("msg->", msg)
else:
    a = float(f.readline())
    print("a->", a)
    try:
        answer = 1.0 / a
    except ZeroDivisionError as e:
        print('ZeroDivisionError3 !!!')
        print("msg->", str(e))
    else:
        print("answer->", answer)
    finally:    #무조건 실행되어진다
        print("Finally!!!")
        f.close()




🔽 파일이 없으면
바로 여기만 타고 끝남

try:
    f = open(filename, 'r')
except IOError:
    msg = "IOError"
    print("msg->", msg)
else:

🔽 t.txt 에 0이라고 적힌 파일이 있으면 else문 타고 내려와서 except ZeroDivisionError as e: 여기 걸렷다가
finally까지 타고 끝

🔽 t.txt 에 1이라고 적힌 파일이 있으면 else문 타고 내려와서
finally까지 타고 끝

open Api

등록완료

client 아이디와 비밀번호는 꼭 적어놓기 ***
(카톡에 적어둠)

0개의 댓글