python 2.7中的超级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38072278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:17:47  来源:igfitidea点击:

super in python 2.7

pythonpython-2.7python-3.xsubprocess

提问by ikel

I'm trying to understand how to use superin python

我试图了解如何super在 python 中使用

class people:   
 name = ''  
 age = 0  
  __weight = 0  

 def __init__(self,n,a,w):  
    self.name = n  
    self.age = a  
    self.__weight = w  
def speak(self):  
    print("%s is speaking: I am %d years old" %(self.name,self.age))  


class student(people):  
 grade = ''  
 def __init__(self,n,a,w,g):  
    #people.__init__(self,n,a,w)  
    super(student,self).__init__(self,n,a,w)
    self.grade = g  

 def speak(self):  
    print("%s is speaking: I am %d years old,and I am in grade %d"%(self.name,self.age,self.grade))  


s = student('ken',20,60,3)  
s.speak()

The above code gets following error:

上面的代码得到以下错误:

---------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-147-9da355910141> in <module>()
     10 
     11 
---> 12 s = student('ken',20,60,3)
     13 s.speak()

<ipython-input-147-9da355910141> in __init__(self, n, a, w, g)
      3     def __init__(self,n,a,w,g):
      4         #people.__init__(self,n,a,w)
----> 5         super(student).__init__(self,n,a,w)
      6         self.grade = g
      7 

TypeError: must be type, not classobj

I'm confused about why I cannot use super(student,self).__init__(self,n,a,w)in this case, and why I have to use people.__init__(self,n,a,w)

我很困惑为什么我不能super(student,self).__init__(self,n,a,w)在这种情况下使用,为什么我必须使用people.__init__(self,n,a,w)

Any help?

有什么帮助吗?

回答by Simon Callan

Your base class peopleshould be derived from the objectclass, to make it a new-style class, which will allow super()to work.

你的基类people应该从object类派生出来,使其成为一个新式类,这将允许super()工作。

You should then use superas:

然后你应该使用super

super(student, self).__init__(n,a,w)

Old-style classes behave quite differently, and I don't understand them

旧式类的行为完全不同,我不理解它们