简体   繁体   English

python:class 名称未定义

[英]python: class name is not defined

I am getting the error "name is not defined " when instantiating a class object in another file.在另一个文件中实例化 class object 时出现错误“名称未定义”。 what is causing this and how do I fix it?是什么原因造成的,我该如何解决? I know there are other posts with the same questions, but the fixes for those didn't work for me.我知道还有其他帖子也有同样的问题,但对这些问题的修复对我不起作用。

in classFile.py在类文件.py

class P:
    def __init__(self):
        pass
class C(P):
    def __init__(self):
        pass
if __name__ == "__main__":
    c1 = C() #no error

in main.py在 main.py 中

import classFile
if __name__ == "__main__":
    foo = C() #errors

gives the error "C isn't defined".给出错误“C未定义”。

when I instantiate foo as below, I get the error I get the error "classFile 'shelf' has no attribute 'C'当我如下实例化 foo 时,我收到错误消息“classFile 'shelf' 没有属性 'C'

foo = classFile.C()

You need to explicitly mention you are using a class from classFile :您需要明确提及您正在使用 classFile 中的classFile

foo = classFile.C()

Alternatively, you could replace your import with:或者,您可以将import替换为:

from classFile import C

and keep your current usage.并保持您当前的使用情况。

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

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