부모 클래스 초기화 과정에서 발생하는 오류에 대해 설명합니다. 다음은 예제 코드입니다:
# 예제 코드
class Avian:
def __init__(self):
self.is_hungry = True
def consume(self):
if self.is_hungry:
print('Аааа...')
self.is_hungry = False
else:
print('아니요, 감사합니다!')
class MelodyBird(Avian):
def __init__(self):
super(MelodyBird, self).__init__()
self.noise = ' Squad!'
def perform(self):
print(self.noise)
오류 발생 시나리오:
>>> from Bird import Avian, MelodyBird
>>> a = Avian()
>>> a.consume()
Аааа...
>>> a.consume()
А니요, 감사합니다!
>>> mb = MelodyBird()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "Bird.py", line 17, in __init__
super(MelodyBird, self).__init__()
TypeError: must be type, not classobj
문제 원인: super() 함수는 새로운 스타일 클래스(ใหม่-스타일 클래스)에만 적용됩니다. 이전 스타일 클래스(구-스타일 클래스)에서는 작동하지 않습니다.
해결 방법 1 (새로운 스타일 사용):
class Avian(object):
def __init__(self):
self.is_hungry = True
def consume(self):
if self.is_hungry:
print('Аааа...')
self.is_hungry = False
else:
print('아니요, 감사합니다!')
class MelodyBird(Avian):
def __init__(self):
super(MelodyBird, self).__init__()
self.noise = ' Squad!'
def perform(self):
print(self.noise)
해결 방법 2 (metaclass 설정):
__metaclass__ = type
class Avian:
def __init__(self):
self.is_hungry = True
def consume(self):
if self.is_hungry:
print('Аааа...')
self.is_hungry = False
else:
print('아니요, 감사합니다!')
class MelodyBird(Avian):
def __init__(self):
super(MelodyBird, self).__init__()
self.noise = ' Squad!'
def perform(self):
print(self.noise)
해결 방법 3 (구 스타일 사용):
class Avian:
def __init__(self):
self.is_hungry = True
def consume(self):
if self.is_hungry:
print('Аааа...')
self.is_hungry = False
else:
print('아니요, 감사합니다!')
class MelodyBird(Avian):
def __init__(self):
Avian.__init__(self)
self.noise = ' Squad!'
def perform(self):
print(self.noise)