2016-07-25 51 views
0
class a(object): 
    def __init__(self): 
     self.num1=0 
     self.num2=0 
    def set1(self,score1,score2): 
     self.num1=score1 
     self.num2=score2 
    def show1(self): 
     print("num1",self.num1,"num2",self.num2) 

class b(a): 
    def __init__(self): 

     super().__init__() 

    def set2(self): 
     self.sum=self.num1+self.num2 
    def show2(self): 
     print("d=",self.sum) 

class c(b): 
    def __init__(self): 
     super.__init__() 
    def set3(self): 
     self.multiplication=self.num1*self.num2 
    def show3(self): 
     print("f=",self.multiplication) 

objects=c() 
objects.set1(1000,100) 
objects.show1() 
objects.set2() 
objects.show2() 
objects.set3() 
objects.show3() 

我寫了這個代碼,以繼承的意義的工作,但我得到:這段代碼中的繼承問題是什麼?

objects=c() 
    File "C:\Users\user\Desktop\New folder\2.py", line 23, in __init__ 
    super.__init__() 
TypeError: descriptor '__init__' of 'super' object needs an argument 

NUM1與NUM2是兩個數字,我想通過在Python繼承的概念,計算它們的總和乘。 我不知道是什麼問題。這個代碼有什麼問題? 謝謝,

回答

0

您在c__init__寫道super.__init__()而不是super().__init__()

如果您使用Python 2,則需要按以下方式撥打super
super(ClassName, self).__init__()

0

你需要調用超級,現在它只是一個參考。

class c(b): 

    super().__init__() 

的另一件事是,如果你想使這個產業更強大的,你可以通過所有指定參數和kwargs到__init__像這樣:

def __init__(self, *args, **kwargs): 
    super().__init__(*args, **kwargs) 

這將使你的類更靈活,並開放給多重繼承。

0

我覺得這是你如何使用super()內置Here the doc

在你的情況下,超需要兩個參數:類和類的實例。

在你b.__init__的synthax將是:

super(b,self).__init__() 

在這裏爲您問題的解決方案:

class b(a): 
    def __init__(self): 
     super(b, self).__init__() 
    def set2(self): 
     self.sum=self.num1+self.num2 
    def show2(self): 
     print("d=",self.sum) 

class c(b): 
    def __init__(self): 
     super(c, self).__init__() 
    def set3(self): 
     self.multiplication=self.num1*self.num2 
    def show3(self): 
     print("f=",self.multiplication)