런타임시 기본 클래스를 동적으로 변경할 수 있습니다. 예를 들면 :
가
class Base_1:
def hello(self):
print('hello_1')
class Base_2:
def hello(self):
print('hello_2')
class Child:pass
def add_base(base):
return type('Child', (base, object), dict(Child.__dict__))()
# if you want change the Child class, just:
def change_base(base):
global Child
Child = type('Child', (base, object), dict(Child.__dict__))
def main():
c1 = add_base(Base_1)
c2 = add_base(Base_2)
c1.hello()
c2.hello()
main()
결과 :
hello_1
hello_2
작품이 잘 자세한 내용은 모두 파이썬 2와 3
에서 관련 질문을 참조 예를 들어
class SomeParentClass:
# something
class Child():
# something
def change_base_clase(base_class):
return type('Child', (base_class, object), dict(Child.__dict__))()
instance = change_base_clase(SomeParentClass)
How to dynamically change base class of instances at runtime?
가 여기 허용 대답을 살펴있다 : HTTP : // 유래. com/questions/15247075/how-can-i-dynamic-derived-derived-class-from-a-base-class – tamasgal
또는 비행 중에 클래스를 만들고 싶지 않거나 필요가 없다면 상속을 배제하고 일부를 전달할 수 있습니다. "도우미"인스턴스를 자식의 생성자에 전달합니다. 파이썬의 오리 타이핑은 대부분의 요구 사항을 처리합니다. –
@septi 감사합니다. – Thrasi