【问题标题】:How can I call a method from base class如何从基类调用方法
【发布时间】:2018-10-03 09:24:21
【问题描述】:
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() 方法(输出应为“第一个函数调用”)?

【问题讨论】:

  • 您当前正在执行一种称为“覆盖”方法的操作。查看此article 了解更多信息!

标签: python inheritance polymorphism


【解决方案1】:

您可以使用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(即,您从object 派生了Base),则首选使用super,如here 中所述。

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多