问题描述
我有一个python程序,我试图导入其他python类,我得到一个NameError:
I have a python program and I'm trying to import other python classes and I am getting a 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()
我做错了什么?
推荐答案
你不能这样做,因为 f
在不同的命名空间。
You can't do that, as f
is in a different namespace.
您需要传递您的实例 wow
您的 joj
实例。为了做到这一点,我们首先创建他们的方式,所以c存在传入f:
You need to pass your instance of wow
your joj
instance. To do this, we first create them the other way around, so c exists to pass into f:
from new import *
c = joj('fds')
f = wow('fgd', c)
f.go()
然后我们将 c
添加到 wow
,将引用存储为 self.c
并使用 self
而不是 f
因为 f
不存在于此命名空间中 - 您引用的对象现在是self:
and then we add the parameter c
to wow
, storing the reference as self.c
and use self
instead of f
as f
doesn't exist in this namespace - the object you are referring to is now self:
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 " !!!!! "
将每个类和函数看作一个新的开始,你在其他地方定义的变量不会落入其中。
Think of each class and function as a fresh start, none of the variables you define elsewhere fall into them.
这篇关于在Python中导入/运行类会导致NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!