python从超类调用方法

时间:2017-09-12 08:38:42

标签: python inheritance

我试图了解一点python继承。这是一个用例:

class Test:

    def hello():
        print("hello")
        return "hello"

    def hi():
        print(hello())
        print("HI")

class Test1(Test):
    hi()
    pass

x = Test1()
x.hello()

我不明白为什么我不能打电话给#34; hi()"在Test1类中。它继承了它的类Test吗?

1 个答案:

答案 0 :(得分:0)

我认为你误解了class es和object的关系和定义。 类就像创建对象的蓝图。通过在类中编写方法,您实际上是定义了可以从类蓝图创建的对象的行为。所以,使用您的代码:

class Test:

    def hello():
        print("Hello")
        return "Hello"

    def hi():
        print(hello())
        print("Hi")


class Test1(Test):

    hi() # <- You really shouldn't call a method directly from a "blueprint" class
    pass

x = Test1()
x.hello()

虽然你的最后两行代码是有效的,但是直接在类定义中调用类范围之外的方法是个坏主意(并且几乎总是无效的)。 hi()Test1类中不起作用的原因是它未在Test1的范围内定义;即使这个类确实继承自Test类,它只会影响从类创建的对象(就像你从{{1}创建的对象x一样} class)。

以下是有关其他相关问题的类和对象的更详细说明:What are classes, references and objects?

希望这有帮助!

相关问题