ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] 클래스, 예외처리
    프로그래밍/Python 2020. 11. 21. 20:37

    클래스, 예외처리

    클래스(Class)

    • 파이썬 클래스는 class 키워드를 사용하여 자신만의 데이터 타입을 만들 수 있음
    • 파이썬 클래스에서는 _ init _ 메서드가 생성자(constructor) 역할을 수행하여, 인스턴스가 만들어 질 때 한번만 호출됨
    • 파이썬 클래스에서는 메서드의 첫번째 인수로 자신의 인스턴스를 나타내는 self를 반드시 기술해야 함
    • 기본적으로 파이썬에서는 메서드와 속성이 모두 public
    class Person:
    
        def __init__(self, name): # 생성자
            self.name = name
            print(self.name + " is initialized")
    
        def work(self, company):
            print(self.name + " is working in " + company)
    
        def sleep(self):
            print(self.name + " is sleeping")
    
    # Person instance 생성
    obj = Person("PARK")
    
    # method call
    obj.work("ABCDEF")
    obj.sleep()
    
    # 속성에 직접 접근, 기본적으로 파이썬에는 모두 public
    print("current person object is ", obj.name)
    
    # 결과
    PARK is initialized
    PARK is working in ABCDEF
    PARK is sleeping
    current person object is  PARK

    클래스 변수(class variable)

    • 해당 클래스로 생성된 모든 인스턴스가 공통으로 사용하는 변수
    • 클래스 변수는 클래스 내외부에서 클래스명.클래스 변수명 으로 접근할 수 있음

    클래스 메서드(class method)

    • 메서드 앞에 @classmethod를 반드시 표기하여 해당 메서드가 클래스 메서드임을 표시
    • 클래스 메서드는 객체 인스턴스를 의미하는 self 대신 cls라는 클래스를 의미하는 파라미터를 인수로 전달 받음
    class Person:
    
        count = 0 # class variable
    
        def __init__(self, name): # 생성자
            self.name = name
            print(self.name + " is initialized")
    
        def work(self, company):
            print(self.name + " is working in " + company)
    
        def sleep(self):
            print(self.name + " is sleeping")
    
        @classmethod    
        def getCount(cls): # class method
            return cls.count
    
    # Person instance 생성
    obj1 = Person("PARK")
    obj2 = Person("KIM")
    
    # method call
    obj1.work("ABCDEF")
    obj2.sleep()
    
    # 속성에 직접 접근, 기본적으로 파이썬에는 모두 public
    print("current person object is ", obj.name)
    
    # class method 호출
    print("Person count == ", Person.getCount())
    
    # class variable direct access
    print(Person.count)
    
    # 결과
    PARK is initialized
    KIM is initialized
    PARK is working in ABCDEF
    KIM is sleeping
    current person object is  PARK
    Person count ==  0
    0

     

    • 파이썬은 기본적으로 모든 멤버가 public 이기 때문에, 외부에서 직접 접근 가능함
    • 멤버 변수(variable), 멤버 메서드(method)를 __멤버 변수, __멤버 메서드 형태로 선언한다면 private으로 설정할 수 있음
    class PrivateMemberTest:
    
        def __init__(self, name1, name2): # 생성자
            self.name1 = name1
            self.__name2 = name2 # private member variable
            print("initialized with " + name1 + " ," + name2)
    
        def getNames(self):
            self.__printNames()
            return self.name1, self.name2
    
        def __printNames(self): # private member method
            print(self.name1, self.__name2)
    
    # instance 생성
    obj = PrivateMemberTest("PARK", "KIM")
    
    print(obj.name1)
    print(obj.getNames())
    print(obj.__printNames()) # error
    print(obj.__name2) # error
    # 결과
    initialized with PARK ,KIM
    PARK
    PARK KIM
    
    
    
    ---------------------------------------------------------------------------
    
    AttributeError                            Traceback (most recent call last)
    
    <ipython-input-3-d1421918f73a> in <module>
         17 
         18 print(obj.name1)
    ---> 19 print(obj.getNames())
         20 print(obj.__printNames()) # error
         21 print(obj.__name2) # error
    
    
    <ipython-input-3-d1421918f73a> in getNames(self)
          8     def getNames(self):
          9         self.__printNames()
    ---> 10         return self.name1, self.name2
         11 
         12     def __printNames(self): # private member method
    
    
    AttributeError: 'PrivateMemberTest' object has no attribute 'name2'

     

    • 외부 함수와 클래스 메서드 이름이 같은 경우에
      • C++, JAVA 언어의 this 처럼 self를 통해 메서드 호출
      • self를 붙이지 않으면 동일한 이름의 외부 함수를 호출하게 됨
    def print_name(name):
    
        print("[def] ", name)
    
    class SameTest:
    
        def __init__(self):
            # 아무것도 하지 않기 때문에 pass
            pass
    
        # 외부 함수와 동일한 이름으로 메서드 정의
        def print_name(self, name):
            print("[SameTest] ", name)
    
        def call_test(self):
    
            # 외부 함수 호출
            print_name("KIM")
    
            # 클래스 내부 메서드 호출
            self.print_name("KIM")
    
    # create SampleTest instance
    obj = SameTest()
    
    # call function print_name
    print_name("LEE")
    
    # call method print_name
    obj.print_name("LEE")
    
    # call method call_test
    obj.call_test()
    # 결과
    [def]  LEE
    [SameTest]  LEE
    [def]  KIM
    [SameTest]  KIM

    예외처리(Exception)

    • try ... except문을 사용
    • try 블록에서 에러가 발생 시, except문으로 이동하여 예외 처리 수행
    • 발생된 exception을 그냥 무시하기 위해서 보통 pass문을 사용
    • 개발자가 에러를 던지기 위해서 raise문을 사용
    • 추가로 finally문을 가질 수 있는데, try블럭이 정상적으로 실행되든 에러가 발생하든 항상 마지막에 실행됨
    def calc(list_data):
    
        sum = 0
    
        try:
            sum = list_data[0] + list_data[1] + list_data[2]
            if sum < 0:
                raise Exception("Sum is minus")
    
        except IndexError as err:
            print(str(err))
        except Exception as err:
            print(str(err))
        finally:
            print(sum)
    
    calc([1, 2, 3])
    calc([1, 2]) # index error 발생
    calc([1, 2, -100]) # exception error 발생
    # 결과
    6
    list index out of range
    0
    Sum is minus
    -97

    with

    • 일반적으로 파일 또는 세션을 사용하는 순서는 다음과 같음 : open() => read() or write() => close()
    • 그러나 파이썬에서 with를 사용하면 명시적으로 리소스 close() 를 해주지 않아도 자동으로 close() 해주는 기능이 있음
    • with 블록을 벗어나는 순간 파일, 세션 등의 리소스를 자동으로 close 시킴
    • 딥러닝 프레임워크인 Tensorflow의 세션 사용시 자주 사용됨
    # 일반적인 방법
    
    f = open("./file_test", 'w')
    f.write("Hello, Python!")
    f.close()
    
    # with 구문을 이용한  방법
    # with 블록을 벗어나는 순간 파일 객체 f가 자동으로 close
    
    with open("./file_test", 'w') as f:
        f.write("Hello, Python!")

     

     

     

    참고

    www.youtube.com/playlist?list=PLS8gIc2q83OjStGjdTF2LZtc0vefCAbnX

     

    머신러닝/딥러닝 강의

    머신러닝과 딥러닝의 동작원리와 이러한 알고리즘을 파이썬으로 구현한 강의 자료입니다.

    www.youtube.com

    '프로그래밍 > Python' 카테고리의 다른 글

    [Python] 파이썬 문법 정리  (0) 2022.01.22
    [Python] 넘파이(Numpy)  (0) 2020.11.23
    [Python] 함수, 람다  (0) 2020.11.21
    [Python] 조건문, 반복문  (0) 2020.11.21
    [Python] 데이터 타입(Data Type)  (0) 2020.11.21

    댓글

Designed by Tistory.