Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.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技巧的视频。他试图证明,当调用扩展类的开发人员提供的方法时,使用更高级别的类时,他可以确保该方法是编写的。然后,他在两个不同的文件中编写了两个类 -- library.py class Base(): def foo(self): return self.bar() -- user.py from library import Base class Derived(Base): def bar(self): re

我正在看一段关于python技巧的视频。他试图证明,当调用扩展类的开发人员提供的方法时,使用更高级别的类时,他可以确保该方法是编写的。然后,他在两个不同的文件中编写了两个类

-- library.py

class Base():
    def foo(self):
        return self.bar()

-- user.py

from library import Base

class Derived(Base):
    def bar(self):
        return 'bar'
现在,我不明白为什么这样做会起作用,因为类
Base
,不能调用从它继承的任何人的方法。例如,以下代码将产生错误

class Higher():

    def higher_method(self):
        print("higher method")

class Lower(Higher):

    def lower_method(self):
        print("lower method")

higher = Higher()        
higher.lower_method()

当他执行代码时,该方法如何调用?

当您调用
派生().foo()
时,绑定到
Base.foo中的
self
的对象不是
Base
的实例;它是
派生的
的一个实例,因此它在
中的查找将成功
Base().foo()
将以相同的逻辑失败:绑定到
self
Base
实例将找不到
bar
的定义

在您的
Higher
/
Lower
示例中,同样的推理也适用:
Higher
的实例根本无法访问名为
Lower\u method
的属性。唯一的区别是您立即失败,您的
Higher
实例绑定到全局名称
Higher
,而不是在
Higher
定义的方法中绑定到名称
self


名称的作用域是静态的,但查找是动态的。

Derived().foo()
将起作用,但可能会看到另一种情况:
Derived
继承
Base
中的所有方法,显然,如果要在
Derived
中编写
def foo
,则,简而言之,这是因为
Base
的实例不知道从它继承的任何类。因此,
Base
的实例没有继承自它的任何类的方法。但要指出这一点:像这样编写
Base
是不安全的,因为该类确实不能保证实现
bar
,否则将导致运行时错误。这就是抽象类和抽象方法定义发挥作用的地方。