【问题标题】:Importing/running classes in Python causes NameError在 Python 中导入/运行类会导致 NameError
【发布时间】:2012-04-09 23:52:22
【问题描述】:

我有一个 python 程序,我正在尝试导入其他 python 类,我得到一个 NameError:

Traceback (most recent call last):
  File "run.py", line 3, in <module>
    f = wow('fgd')
NameError: name 'wow' is not defined

这是在名为new.py的文件中:

class wow(object):
    def __init__(self, start):
        self.start = start

    def go(self):
        print "test test test"
        f = raw_input("> ") 
        if f == "test":
            print "!!"  
            return c.vov()  
        else:
            print "nope"    
            return f.go()

class joj(object):
    def __init__(self, start):
        self.start = start
    def vov(self):
       print " !!!!! "

这是在文件run.py

from new import *

f = wow('fgd')
c = joj('fds')
f.go()

我做错了什么?

【问题讨论】:

  • 在询问 Python 问题时,它总是有助于指出代码中发生了什么错误。这种情况可以很容易推断出NameError,但在其他一些时候并不那么明显,添加此类信息会花费您零努力。
  • 此处的缩进与文件中的缩进相同吗?它看起来像if f == "test",下面的意思是向右缩进。
  • new 是一个错误的模块名称选择。已经有一个(已弃用)内置模块,名为 new
  • 请注意,我建议避免使用from ___ import * - 这(通常)是一个不好的习惯。相反,导入你想显式使用的任何内容,或者导入模块并使用&lt;module&gt;.&lt;thing&gt;

标签: python class import nameerror


【解决方案1】:

您不能这样做,因为f 位于不同的命名空间中。

您需要将wow 实例传递给joj 实例。为此,我们首先以相反的方式创建它们,因此存在 c 以传递给 f:

from new import *

c = joj('fds')
f = wow('fgd', c)
f.go()

然后我们将参数c 添加到wow,将引用存储为self.c 并使用self 而不是f,因为f 在此命名空间中不存在-您是该对象指的是现在的自我:

class wow(object):
    def __init__(self, start, c):
        self.start = start
        self.c = c

    def go(self):
        print "test test test"
        f = raw_input("> ") 
        if f == "test":
            print "!!"  
            return self.c.vov()  
        else:
            print "nope"    
            return self.go()

class joj(object):
    def __init__(self, start):
        self.start = start
    def vov(self):
       print " !!!!! "

将每个类和函数视为一个新的开始,您在别处定义的变量都不属于它们。

【讨论】:

  • 如果您希望它也可以在wow.go 中使用,您需要在wow.__init__ 中使用c。我没有编辑来展示这一点,因为这实际上需要一套全新的解释,我认为你完全有能力写出来:)你可能还想谈谈使用递归来建立一个简单的循环...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2016-11-05
  • 1970-01-01
  • 2019-04-11
  • 2020-12-21
  • 2017-05-28
  • 1970-01-01
相关资源
最近更新 更多