2016-07-22 91 views
1

的Python 2.7的Python:自動調用父功能子實例化後

我想automotically調用父對象的功能我實例化後,其子

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 

有沒有一種方法可以讓我做這個?

編輯,從下面的註釋:

「我應該做它在我的問題更清晰,我真正想要的是某種形式的‘自動’調用父類的方法通過的實例化單獨觸發孩子,沒有明確地從孩子那裏調用父母的方法,我希望能有這種神奇的方法,但我不認爲有這種方法。「

+0

您正在使用哪個版本的python? – 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使用Python 2? – cdarke

+2

@cdarke從他們的'print'語句 –

4

你可以使用super,但你應該設置你的object繼承:

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__'。 –