Importing/running classes in Python causes NameError

房东的猫 提交于 2019-12-08 10:52:24

问题


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

This is in file called 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 " !!!!! "

This is in file run.py:

from new import *

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

What am I doing wrong?


回答1:


You can't do that, as f is in a different namespace.

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()

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.



来源:https://stackoverflow.com/questions/10081335/importing-running-classes-in-python-causes-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!