如何从基类调用方法

时间:2018-10-03 09:24:21

标签: python inheritance polymorphism

class Base():
    def __init__(self):
        print("test")

    def first_func(self):
        print("first function call")


class Deriv(Base):
    def __init__(self):
        Base.__init__(self)

    def first_func(self):
        print("Test Derived")

C = Deriv()
C.first_func() # It gives output "Test Derived"

如何仅使用对象C和python 2.7从基类(Class Base)中调用first_func()方法(输出应为“第一个函数调用”)?

1 个答案:

答案 0 :(得分:0)

您可以使用Base.first_func(C)显式调用基类函数:

class Base():
    def __init__(self):
        print("test")

    def first_func(self):
        print("first function call")


class Deriv(Base):
    def __init__(self):
        Base.__init__(self)

    def first_func(self):
        print("Test Derived")

C = Deriv()
Base.first_func(C) 

输出为:

test
first function call

如果您是using new-style classes(即您是从Base派生的object),则最好使用super,如here中所述。 / p>

相关问题