본문

생성자(Constructor), 클래스 활용하기

setdata 없이 FourCal 클래스를 사용하면

>>> a = FourCal()

>>> a.sum()

Traceback (most recent call last):

 File "<stdin>", line 1, in <module> #stdin (Standard Input) : 표준 입력

 file"<stdin>", line 6, in sum

AttributeError: 'FourCal' object has no attribute 'first'

라고 오류가 뜹니다. 

메서드명으로 __init__를 사용해서 생성자를 만드는 방법을 소개하고 있습니다. 

>>> class FourCal:

           def __init___(self, first, second):

                self.first = first

                self.second = second

           def setdata(self, first, second) :

                self.first = first

                self.second = second

            def sum(self):

                 result = self.first + self.second

                 return result

다른 것과 같지만, 메서드를 __init__로 했지 때문에 객체가 생성되는 시점에 자동으로 호출됩니다. 

클래스의 상속 다른 클래스의 기능도 받을 수 있게 물려주는 것을 의미합니다. 기존 클래스의 변형없이 기능을 추가하거나 변경할때 사용합니다.  

>>> class MoreFourCal(FourCal):

           pass

>>> a = MorefourCal(4, 2)

>>> a.sum()

6

>>> class MoreFourCal(FourCal) :

           def pow(self):

                result = self.first ** self.second

                return result

>>> a = MoreFourCal(4, 2)

>>> a.pow()

16

위와같이 상속이 되는 것을 볼 수 있습니다. 

메서드 오버라이딩

ZeroDivisionError 오류를 없애려고 if문을 적어줍니다. 

>>> class SafeFourCal(FourCal):

           def div(self)


                if self.second == 0

                        return 0

                else:

                      resulf = self.first / self.second

                      return result

클래스의 활용

>>> data = "홍길동|42|A"

>>> def print_grade(data) :

            tmp = data.split("|")

            name = tmp[0]

            grade = tmp[2]

            print("%s님의 점수는 %s입니다." % (name, grade)

위와 같이 결과값을 주고 싶으면 매번 data.split("|")을 해줘야 하는 불편한 점이 있다. 이때 클래스를 활용하면

>>> class Data:

           def __init__(self, data) :

                  tmp = data.split("|")

                  self.name = tmp[0]

                  self.age = tmp[1]

                  self.grade = tmp[2]

이렇게 클래스를 설정해두면 매번 스플릿을 하지 않고 원하는 값을 출력할 수 있다. 

>>> data = Data("홍길동|42|A")

>>> print(data.age)

42

이 글의 내용은 위키독스에 올라온 점프투파이썬 읽으면서 정리한 내용입니다. 

출처: 위키독스 점프투파이썬 https://wikidocs.net/book/1

댓글