为什么继承多态性取决于我们在 python 中导入的方式

问题描述 投票:0回答:1

考虑这三个文件:

base.py

class Base():
    def method(self):
        print('Base Class')

object = Base()

main.py

from base import object

def main():
    object.method()

if __name__ == '__main__':
    main()

测试.py

import main
import base

class Derived(base.Base):
    def method(self):
        print('Derived Class')

base.object = Derived()

main.main()

我希望启动 test.py 会调用派生类的 method() 函数,但事实并非如此。

$ python3.8 test.py
Base Class

但是如果我改变我在 main.py 中导入对象的方式它会起作用

新的main.py

import base

def main():
    base.object.method()

if __name__ == '__main__':
    main()

新输出:

$ python3.8 test.py
Derived Class
python inheritance polymorphism python-module
1个回答
0
投票

简答:因为它们是不同的对象。

第一种情况:当您导入

main
时,您正在创建对象,我称之为
main_object
。然后你正在导入基础,这将创建
base_object
。这些对象不一样(你可以使用
id
来检查)。

第二种情况:你引用同一个对象,因此它会产生预测结果。 尝试以下操作:

base.py

from base import obj
print(f"object from main has id = {id(obj)}")
def main():
    obj.method()

if __name__ == '__main__':
    main()

main.py

from base import obj
print(f"object from main has id = {id(obj)}")
def main():
    obj.method()

if __name__ == '__main__':
    main()

测试.py

import base

import main

class Derived(base.Base):
    def method(self):
        print('Derived Class')
base.obj = Derived()
print(f"base.obj in test.py has id = {id(base.obj)}")

main.main()

此外,

object
是python中的关键字。最好为变量使用不同的名称,例如 obj.

© www.soinside.com 2019 - 2024. All rights reserved.