繁体   English   中英

子类不识别父类的模块导入?

[英]Child class doesn't recognize module imports of parent class?

我在两个不同的模块中有两个课程:

  • animal.py
  • monkey.py

animal.py:

import json

class Animal(object):
    pass

猴:

import animal

class Monkey(animal.Animal):

    def __init__(self):
        super(Monkey, self).__init__()

        # Do some json stuff...

当我尝试实例化一只Monkey ,我得到了一个

NameError: global name 'json' is not defined

但我在超类的定义模块中导入json ,为什么不加载它?

它已加载,但其名称在monkey.py的范围内monkey.py

您可以输入animal.json来获取它(但为什么会这样),或者只是输入

import json

monkey.py中也是如此。 Python将确保模块未加载两次。

好吧,python导入不能用作C #include预处理器指令。 它们仅将模块导入导入模块的命名空间,而不导入全局命名空间。 所以,你必须在你想要使用它的每个模块中导入json。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM