Importing/running classes in Python causes NameErr

2019-06-11 11:37发布

问题:

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.