python 2.7中的超级 [英] super in python 2.7

查看:46
本文介绍了python 2.7中的超级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand how to use super in 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()

以上代码报错如下:

---------------------------------------------------------------------
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

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

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)

有什么帮助吗?

推荐答案

你的基类 people 应该派生自 object 类,使其成为一种新风格类,这将允许 super() 工作.

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

然后你应该使用 super 作为:

You should then use super as:

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

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

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

这篇关于python 2.7中的超级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆