2013-09-08 2 views
1

인스턴스가 생성 될 때까지 부모 클래스를 지정하지 않을 수 있습니까?
예 : 이런 식으로 :상위 클래스를 인수로 전달 하시겠습니까?

class SomeParentClass: 
    # something 

class Child(unspecifiedParentClass): 
    # something 

instance = Child(SomeParentClass) 

이것은 분명히 작동하지 않습니다. 그러나 어떻게 든 이것을 할 수 있습니까?

+1

가 여기 허용 대답을 살펴있다 : HTTP : // 유래. com/questions/15247075/how-can-i-dynamic-derived-derived-class-from-a-base-class – tamasgal

+0

또는 비행 중에 클래스를 만들고 싶지 않거나 필요가 없다면 상속을 배제하고 일부를 전달할 수 있습니다. "도우미"인스턴스를 자식의 생성자에 전달합니다. 파이썬의 오리 타이핑은 대부분의 요구 사항을 처리합니다. –

+0

@septi 감사합니다. – Thrasi

답변

2

시도해 보셨습니까?

class SomeParentClass(object): 
    # ... 
    pass 

def Child(parent): 
    class Child(parent): 
     # ... 
     pass 

    return Child() 

instance = Child(SomeParentClass) 

파이썬 2.X에서 새로운 스타일의 클래스를 사용하는 부모 클래스의 슈퍼 클래스로 object을 포함해야합니다.

+1

'def Child'는'class'가 아닌 새로운 클래스를 반환합니다. – delnan

+0

또는 그냥 하위 함수에서 인스턴스를 반환 할 수 있습니다 :'return Child()' – atupal

+0

반영하도록 업데이트했습니다. – Lethargy

0

런타임시 기본 클래스를 동적으로 변경할 수 있습니다. 예를 들면 :

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?

+0

원본의 기본 클래스는 변경되지 않습니다. 같은 이름의 새 클래스를 만듭니다. – chepner

+0

당신은'global Child; Child = type ('Child', (base, object), dict (Child .__ dict __)) ' – atupal

3

당신은 클래스 '__init__() 방법 인스턴스의 클래스를 변경할 수 있습니다

class Child(object): 
    def __init__(self, baseclass): 
     self.__class__ = type(self.__class__.__name__, 
           (baseclass, object), 
           dict(self.__class__.__dict__)) 
     super(self.__class__, self).__init__() 
     print 'initializing Child instance' 
     # continue with Child class' initialization... 

class SomeParentClass(object): 
    def __init__(self): 
     print 'initializing SomeParentClass instance' 
    def hello(self): 
     print 'in SomeParentClass.hello()' 

c = Child(SomeParentClass) 
c.hello() 

출력 :

한편
initializing SomeParentClass instance 
initializing Child instance 
in SomeParentClass.hello() 
+0

이것은 더 나은 해결책입니다. – xiaolin

+0

@ linxtion 이유를 설명하는 데주의해야합니까? 나는 실제로 수용된 대답이 훨씬 투명하고 유연하다고 생각한다. –

+0

나는 3 년 이래로 이것에 대해 많이 기억하지 않는다. 다시 한번 보았을 때, 받아 들여진 해결책은 읽기가 더 쉽지만 pep8과 비교해 보았습니다. 정말 너까지. – xiaolin

관련 문제