如何访问 python 中对象的祖先

How to access the ancestor of an object in python

假设classA继承自B,B继承自C。

class C():
    def my_method(self):
        pass

class B(C):
    def my_method(self):
        pass

class A(B):
    def my_method(self):
        # Call my_method from B
        super(A, self).my_method()
        # How can I call my_method from C here ?

问题:如何从 C 调用 my_method?

您可以使用对象的 __mro__ 属性访问对象的完整祖先:

In [3]: KeyError.__mro__
Out[3]: (KeyError, LookupError, StandardError, Exception, BaseException, object)

您可以通过直接调用 "unbound" 方法来调用 Cmy_method() 方法,并将 self 作为参数传递。例如:

class C(object):
    def my_method(self):
        print('C.my_method')

class B(C):
    def my_method(self):
        print('B.my_method')

class A(B):
    def my_method(self):
        print('A.my_method')
        super(A, self).my_method()  # calls B.my_method(self)
        C.my_method(self)           # calls C.my_method(self)

a = A()
a.my_method()

当 运行 时,将打印以下内容(注意 super() 需要 (object) 才能在 Python 2.x 上工作:

A.my_method
B.my_method
C.my_method

但是,正如其他人指出的那样,这可能不是实现您想要的目标的最佳方式。你能举一个具体的例子来说明你在上下文中想要实现的目标吗?

首先,如果你想使用超级函数,那么你必须像这样使用基 class 作为对象

class c(object):
    pass

因为只有 python 的新式编程才支持超级函数。

现在介绍如何访问基数 class 的基数 class 的函数。在你的情况下如何从 A.

调用 class C 的 my_method 函数

您可以通过静态和动态两种方式执行此操作。

动态

class C(object):
    def my_method(self):
        print "in function c"

class B(C):
    def my_method(self):
        print "in function b"

class A(B):
    def my_method(self):
        # Call my_method from B
        super(A, self).my_method()
        # This is how you can call my_method from C here ?
        super((self.__class__.__bases__)[0], self).my_method()
obj_a = A()
obj_a.my_method()

这里 (self.__class__.__bases__) 将 return 以 class 元组类型中的 A 为基础,这就是我采用第 0 个索引的原因。所以它 return class B 所以将 B class 作为 super 中的参数它将 return my_method base class 的函数 class of b class.

静态

class C(object):
    def my_method(self):
        print "in function c"

class B(C):
    def my_method(self):
        print "in function b"

class A(B):
    def my_method(self):
        # Call my_method from B
        super(A, self).my_method()
        # This is how you can call my_method from C here ?
obj_a = A()
super(A,obj_a).my_method() # calls function of class B
super(B,obj_a).my_method() # calls function of class A