5.파이썬독학 클래스 외

서창용·2022년 3월 5일
0

https://youtu.be/KL1MIuBfWe0 3:13부터

  1. 클래스
  • 반복되는 함수, 매소드를 쓰기위해
  • 맨앞을 대문자로 쓰는게 정석

Class 클래스이름:
수행문

class FourCal:
    def setdata(self, first, second):
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second
        return result


a = FourCal()
a.setdata(1, 2)
print(a.first)
print(a.second)
print(a.add())
class FourCal:
    def __init__(self, first, second):  ##__init__은 클래스 선언하자마자 무조껀 실행되는 함수
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second
        return result


a = FourCal(1, 2)
print(a.first)
print(a.second)
print(a.add())
  1. 클래스 상속

    class 자식클래스명(부모클래스명):
    ex)
    class MoreFourCal(FourCal):
    pass

    부모 클래스 함수랑 자식 클래스 함수랑 같으면
    자식 클래스꺼가 실행 = 오버라이딩
    자식 이기는 부모없다 이런 느낌..

  2. 모듈
  • 미리만들어놓은 파이썬 파일(.py)

    import [파일명]
    from [파일명] import [그 파일의 함수명]

    해당 파일일때만 실행하고 모듈로 쓰이면 실행하지않기
    if  __name__ == "__main__":
    	pirnt(어쩌고)
  • 위치 다를때
    import sys
    sys.path.append("경로")
    import [파일명]
  1. 패키지(=모듈 어러개 모은것)

    __init__.py <<패키지를 설정하는 파일
    import [상위폴더].[상위폴더].[파일명]
    import * 를 쓸려면 __ini__.py 파일 안에
    __all__ = ['파일명','파일명'] 해야함

       

5.예외처리

try:
오류가 발생할 수 있는 구문
except Exception as e:
오류발생
else:
오류발생하지않음
finally:
마지막실행

f = open("no.txt", "w")

try:
   data = f.read()
   print(data)
except Exception as e:
   print(e)
finally:
   f.close()

print("gi")

결과값 : not readable
gi

일부러 애러 내기
raise 애러구문(FileNotFoundError)

profile
관신분야 : 브랜딩, 마케팅, 파이썬, 리액트 네이티브, MSA, 엘라스틱서치

0개의 댓글