2016-07-22 3 views
1

파이썬 2.7파이썬 : 자동으로 내가 할 수있는 방법이 있나요

은 내가 인스턴스화 한 후

class Mother: 

    def __init__(self): 
     pass 

    def call_me_maybe(self): 
     print 'hello son' 


class Child(Mother): 

    def __init__(self): 
     print 'hi mom' 


# desired behavior 

>>> billy = Child() 
hi mom 
hello son 

자식 부모 객체의 함수를 호출 automotically 싶습니다 자식 인스턴스 후 부모 함수를 호출 이?

편집, 아래의 코멘트에서 :

는 "내가 했어야

것이 더 명확하게 내 질문에, 내가 정말 원하는 것은 부모 방법을 호출하는 '자동'는의 인스턴스에 의해서만 트리거의 일종이다 아이에게 부모 메서드를 명시 적으로 호출하지 않은 상태에서, 어떤 종류의 마법 메서드가있을 것이라고 기대했지만 거기에는 있다고 생각하지 않습니다. "

+0

어떤 버전의 파이썬을 사용하고 있습니까? – cdarke

답변

1

super()?

class Child(Mother): 
    def __init__(self): 
     print 'hi mom' 
     super(Child, self).call_me_maybe() 
+4

OP는 Python 2를 사용하기 때문에 편리한 'super()'를 사용할 수 없습니다. 2.x 버전은'super (Child, self) .call_me_maybe()'입니다. –

+0

@ HannesOvrén : OP가 파이썬 2를 사용하고 있다는 것을 어떻게 알 수 있습니까? – cdarke

+2

@cdarke 그들의'print' 문 –

4

object에서 상속 당신은 super 사용할 수 있지만, 당신은 당신의 슈퍼 클래스을 설정해야합니다

class Mother(object): 
#   ^
    def __init__(self): 
     pass 

    def call_me_maybe(self): 
     print 'hello son' 


class Child(Mother): 

    def __init__(self): 
     print 'hi mom' 
     super(Child, self).call_me_maybe() 

>>> billy = Child() 
hi mom 
hello son 
1

자식 클래스는 부모의 메소드를 상속하기 때문에, 당신은 단순히 호출 할 수 있습니다 __init__() 문에있는 메소드

class Mother(object): 

    def __init__(self): 
     pass 

    def call_me_maybe(self): 
     print('hello son') 


class Child(Mother): 

    def __init__(self): 
     print('hi mom') 
     self.call_me_maybe() 
+1

이것은 똑같은 일을하지만 OP의 요청은 부모 메서드를 호출하는 것입니다. 'super'를 사용하면이 기술로 부모의'__init__'를 호출 할 수 있음을 알 수 있습니다. –

관련 문제