파이썬에서 슈퍼 클래스에서 서브 클래스를 어떻게 만드나요?
답변
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
또는 더 좋은 점은 Python의 내장 함수 super()
( Python 2 / Python 3 문서 참조)를 사용하는 것이 초기화를 위해 부모를 호출하는 약간 더 나은 방법 일 수 있습니다.
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
또는 super()
클래스 정의 내에서만 작동 하는 0 인수 형식을 사용하는 것을 제외하고는 위와 똑같습니다 .
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
답변
영웅적인 작은 예 :
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print sm.getName()
sm2 = SuperManII()
print sm2.getName()
답변
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
상속 섹션 파이썬 문서에서 더 자세하게 설명
답변
class Class1(object):
pass
class Class2(Class1):
pass
Class2는 Class1의 하위 클래스입니다.
답변
위의 답변에서는 super
(키워드) 인수없이 초기화됩니다. 그러나 종종 자신의 ‘사용자 지정’인수를 전달하는 것뿐만 아니라 그렇게하기를 원합니다. 다음은이 사용 사례를 보여주는 예입니다.
class SortedList(list):
def __init__(self, *args, reverse=False, **kwargs):
super().__init__(*args, **kwargs) # Initialize the super class
self.reverse = reverse
self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments
이 하위 클래스는 list
초기화 될 때 reverse
다음 테스트에서 알 수 있듯이 키워드 인수에 지정된 방향으로 즉시 자체 정렬됩니다 .
import pytest
def test_1():
assert SortedList([5, 2, 3]) == [2, 3, 5]
def test_2():
SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
def test_3():
with pytest.raises(TypeError):
sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument
if __name__ == "__main__":
pytest.main([__file__])
의에 통과 덕분 *args
에이 super
목록이 초기화 대신 단지 빈되는 항목으로 채울 수 있습니다. ( PEP 3102reverse
에 따른 키워드 전용 인수입니다 .)
답변
파이썬에서 함수를 사용하여 동적으로 하위 클래스를 만드는 또 다른 방법이 있습니다 type()
.
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
일반적으로 메타 클래스로 작업 할 때이 방법을 사용합니다. 낮은 수준의 자동화를 원할 때 파이썬이 클래스를 만드는 방식을 변경합니다. 이런 식으로 할 필요는 없을 것입니다.하지만 그렇게하면 이미 무엇을하고 있는지 알 것입니다.
답변
class Subclass (SuperClass):
# Subclass stuff here
