[Python]Overriding (다형성)
파이썬의 Overriding에 대해서 알아보자.
"""
Python Overriding
"""
import datetime
# 예1 : 상속
class ParentEx1:
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class ChildEx1(ParentEx1):
pass
c1 = ChildEx1()
p1 = ParentEx1()
# 자식클래스에서 부모클래스 메소드 호출
print(f'Ex1 > {c1.get_value()}')
"""
Ex1 > 5
"""
# c1 모든 속성출력
print(f'Ex1 child > {dir(c1)}')
"""
Ex1 child > ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value', 'value']
"""
# 부모 / 자식 클래스의 모든 속성 출력
print('Ex1 > ', dir(ParentEx1))
print('Ex1 > ', dir(ChildEx1))
"""
Ex1 > ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']
Ex1 > ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']
"""
print()
print('Ex1 부모 > ', ParentEx1.__dict__)
print('Ex1 자식 > ', ChildEx1.__dict__)
print()
"""
Ex1 부모 > {'__module__': '__main__', '__init__': <function ParentEx1.__init__ at 0x104dcdca0>, 'get_value': <function ParentEx1.get_value at 0x104cd8940>, '__dict__': <attribute '__dict__' of 'ParentEx1' objects>, '__weakref__': <attribute '__weakref__' of 'ParentEx1' objects>, '__doc__': None}
Ex1 자식 > {'__module__': '__main__', '__doc__': None}
"""
# 예2 : 메서드 재정의
class ParentEx2:
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class ChildEx2(ParentEx2):
def get_value(self):
return self.value * 10
c2 = ChildEx2()
# 자식클래스의 메서드 호출
print(f'Ex2 > {c2.get_value()}')
"""
Ex2 > 50
"""
# 예3 : Overring (다형성)
class Logger:
def log(self, msg):
print(msg)
class TimestampLogger(Logger):
def log(self, msg):
message = f'{datetime.datetime.now()} {msg}'
# super().log(message) -> 아래와 같이 변경되어 호출된다.
super(TimestampLogger, self).log(message)
class DateLogger(Logger):
def log(self, msg):
message = f'{datetime.datetime.now().strftime("%Y-%m-%d")} {msg}'
# super().log(message) -> 아래와 같이 변경되어 호출된다.
super(DateLogger, self).log(message)
l = Logger()
t = TimestampLogger()
d = DateLogger()
l.log("테스트1")
t.log("테스트1")
d.log("테스트1")
"""
테스트1
2023-06-27 19:27:13.626131 테스트1
2023-06-27 테스트1
"""
최신 댓글