파이썬 Super()로 다른 메서드 갖다쓰기

코지클래식·2023년 1월 13일
0
class A1:
    def test(self, x):
        return x*2

class A2:
    def test(self, x):
        return super().test(x) * 2

class B1:
    def test(self, x):
        return x+1

class B2:
    def test(self, x):
        return super().test(x) + 1


class R1(A1,B1):
    pass
print(R1().test(3)) # 6 : 3*2 (A1)

class R2(B1,A1):
    pass
print(R2().test(3)) # 4 : 3+1 (B1)

class R3(A2,B1):
    pass
print(R3().test(3)) # 8 : (3+1)*2 (B1 -> A2)

class R4(B2,A1):
    pass
print(R4().test(3)) #7 : (3*2)+1 (A1 -> B2)

""" 결론: super()이 들어간 함수가 있는 클래스를
왼쪽에서 상속하면, 오른쪽에 있는 같은 이름의 함수를 super()로 호출할 수 있다.
"""
profile
코지베어

0개의 댓글