2014-05-19 68 views
1

我想在Python使用超()调用父类的方法2.从子类调用父类方法在Python 2

在Python 3,我想这样的代码吧:

class base: 
     @classmethod  
     def func(cls): 
      print("in base: " + cls.__name__) 

    class child(base): 
     @classmethod  
     def func(cls): 
      super().func() 
      print("in child: " + cls.__name__) 

    child.func() 

与此输出:

in base: child 
    in child: child 

但是,我不知道,如何在Python 2。做到这一点。当然,我可以使用base.func(),但我不喜欢,除了指定的父类名和主要是我得到不想要的结果:

in base: base 
    in child: child 

随着clscls is child)在super()函数调用的第一个参数,我得到这个错误:

TypeError: must be type, not classobj 

不知道如何使用super()或类似的功能做在我没有来指定父类的名称?

+1

提示:复制你的问题贴到谷歌搜索 – Dunno

回答

3

进一步对方的回答你能为它做classmethods像

class base(object): 
     @classmethod  
     def func(cls): 
      print("in base: " + cls.__name__) 

class child(base): 
     @classmethod  
     def func(cls): 
      super(cls, cls).func() 
      print("in child: " + cls.__name__) 

child.func() 
+0

谢谢,这是我想要的东西:) –

+0

应该是'超(儿童,CLS)'。否则'child'的子类以无限递归调用'func'结束。 – saaj

1

你父对象需要从对象继承在Python 2。所以:

class base(object): 
    def func(self): 
     print("in base") 

class child(base): 
    def func(self): 
     super(child, self).func() 
     print("in child") 

c = child() 
c.func() 
0

我试图做同样的事情在那里我试图基本上“继续”继承链,直到找到某个基类,然后在那里用类名做一些事情。我遇到的问题是,所有这些答案都假设你知道你想要获得超类的班级的名字。我尝试了“super(cls,cls)”方法,但得到了上述的“无限递归”问题。这里是我登陆

@classmethod 
def parent_name(cls): 
    if BaseDocument in cls.__bases__: 
     # This will return the name of the first parent that subclasses BaseDocument 
     return cls.__name__ 
    else: 
     for klass in cls.__bases__: 
      try: 
       parent_name = klass.parent_name() 
       if parent_name is not None: 
        return parent_name 
      except AttributeError: 
       pass 

     return None