在Python中创建简单的对象层次结构时,我希望能够从派生类调用父类的方法。在Perl和Java中,对此有一个关键字(super)。在Perl中,我可以这样做:

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

sub frotz {
   my $str = SUPER::frotz();
   return uc($str);
}

在Python中,似乎我必须显式地从子类中命名父类。 在上面的例子中,我必须做一些类似于Foo::frotz()的事情。

这似乎是不正确的,因为这种行为使得很难建立深层的等级制度。如果孩子们需要知道哪个类定义了一个继承的方法,那么就会产生各种各样的信息麻烦。

这是python的实际限制,还是我理解上的差距,或者两者兼而有之?


当前回答

Python也有super:

超级(类型、对象或者类型)

返回一个代理对象,该对象将方法调用委托给类型的父类或兄弟类。 这对于访问在类中被重写的继承方法非常有用。 除了类型本身被跳过之外,搜索顺序与getattr()所使用的相同。

例子:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()

其他回答

如果你不知道你可能会得到多少争论,并且想把它们都传递给孩子:

class Foo(bar)
    def baz(self, arg, *args, **kwargs):
        # ... Do your thing
        return super(Foo, self).baz(arg, *args, **kwargs)

(来自:Python -覆盖__init__的最干净的方法,其中可选的kwarg必须在super()调用后使用?)

我建议使用CLASS.__bases__ 就像这样

class A:
   def __init__(self):
        print "I am Class %s"%self.__class__.__name__
        for parentClass in self.__class__.__bases__:
              print "   I am inherited from:",parentClass.__name__
              #parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()
ImmediateParentClass.frotz(self)

无论直接父类本身定义了frotz还是继承了它,都会很好。Super只在适当支持多重继承时才需要(并且只有当每个类都正确使用它时,它才会工作)。一般来说,AnyClass。如果AnyClass没有定义/覆盖它,whatever将在AnyClass的祖先中查找whatever,这对于“子类调用父方法”和任何其他情况都是正确的!

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()

Python也有super:

超级(类型、对象或者类型)

返回一个代理对象,该对象将方法调用委托给类型的父类或兄弟类。 这对于访问在类中被重写的继承方法非常有用。 除了类型本身被跳过之外,搜索顺序与getattr()所使用的相同。

例子:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()