Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自超类的python调用方法_Python_Inheritance - Fatal编程技术网

来自超类的python调用方法

来自超类的python调用方法,python,inheritance,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() 我不明白为什么我不能在类Test1中调用“hi()”。

我试图稍微了解一下python继承。下面是一个用例:

class Test:

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

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

class Test1(Test):
    hi()
    pass

x = Test1()
x.hello()

我不明白为什么我不能在类Test1中调用“hi()”。它继承了It类测试,对吗?

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

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()
类测试:
def hello():
打印(“你好”)
回复“你好”
def hi():
打印(hello())
打印(“Hi”)
类Test1(测试):

hi()#因为这不是类内调用方法的方式。通过在类级别编写调用,您试图做什么?好吧,我想既然Test1继承了Test,它应该能够在类级别调用它,对吗?我想您想要做的是从对象
x
调用
hi()
。(例如,在
x.hello()
调用
x.hi()
之后,它将按预期工作)@ozn否。你为什么会这样想?那么你没有以任何可以理解的方式使用类。类用于创建对象。你需要解释为什么你想做一些不同的事情。