python nameerror import_在Python中导入/运行类会导致NameError

在Python编程中遇到了一个NameError,尝试从new.py导入wow类并实例化,但出现错误。问题在于不同命名空间之间的引用。解决方法是将wow的实例作为参数传递给joj实例,并相应地更新wow类的构造函数,以便使用self.c而不是f调用vov方法。这样确保了对象间的正确交互。
摘要由CSDN通过智能技术生成

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

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值