파이썬 객체지향

zzZ·2022년 7월 24일
0

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 add(self):
        result = self.first + self.second
        return result
    def mul(self):
        result = self.first * self.second
        return result
    def sub(self):
        result = self.first - self.second
        return result
    def div(self):
        result = self.first / self.second
        return result

class MoreFourCal(FourCal):    #FourCal상속
    def pow(self):
        result = self.first ** self.second
        return result

class SafeFourCal(FourCal):
    def div(self):      # 오버라이딩
        if self.second == 0:
            return False
        else:
            return self.first/self.second

a = FourCal(4, 2)
b = MoreFourCal(4, 2)
# print(type(a))
# print(a.first)
# print(a.second)
# print(a.add())
# print(a.mul())
print(b.pow())
print(b.add())
c = SafeFourCal(4,0)
print(c.div())
  • 파이썬 메서드의 첫 번째 매개변수 이름은 관례적으로 self를 사용한다. 객체를 호출할 때 호출한 객체 자신이 전달되기 때문에 self를 사용한 것이다

  • 생성자는 파이썬 메서드 이름으로 __init__를 사용하면 이 메서드는 생성자가 된다

  • 상속은 클래스 이름 뒤 괄호 안에 상속할 클래스 이름을 넣어주면 된다

  • 부모 클래스(상속한 클래스)에 있는 메서드를 동일한 이름으로 다시 만드는 것을 메서드 오버라이딩(Overriding, 덮어쓰기)이라고 한다. 이렇게 메서드를 오버라이딩하면 부모클래스의 메서드 대신 오버라이딩한 메서드가 호출된다

0개의 댓글