来自超类的python调用方法
我试图稍微了解一下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()”。
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否。你为什么会这样想?那么你没有以任何可以理解的方式使用类。类用于创建对象。你需要解释为什么你想做一些不同的事情。