小编Cat*_*ine的帖子

即使我导入了集合,也没有定义python全局名称'collections'

以下是config.py:

from collections import OrderedDict
def test_config(fileName):
    tp_dict = collections.OrderedDict()
    with open("../../config/" + fileName, 'r') as myfile:
        file_str = myfile.read().replace(' ', '').split('\n')
    tp_list = []
    for i, x in enumerate(file_str):
        x = x.strip()
        try:
            key = x[:x.index(':')].strip()
            value = x[x.index(':')+1:]
            if key == 'testpoint':
                pass
            else:
                tp_dict[key] = value.strip().split(',')
        except ValueError,e:
            pass
        if i % 4 == 0 and i != 0:
            tp_list.append(tp_dict.copy())   
    return tp_list
Run Code Online (Sandbox Code Playgroud)

我在另一个文件test.py中使用该函数:

import config
a = config.test_config('test.txt')

NameError: global name 'collections' is not defined
Run Code Online (Sandbox Code Playgroud)

但是,如果我将整个代码从config.py复制粘贴到test.py的顶部,然后使用该函数,那么我没有错误(参见下面的代码).请问有人向我解释一下吗?我太困惑了.非常感谢你!

""" …
Run Code Online (Sandbox Code Playgroud)

python collections import function nameerror

4
推荐指数
3
解决办法
1万
查看次数

如何在Python中调用另一个类的函数

class A:
  def add_f(self,a,b):
    return a+b

class B:
  def sum_f(self,a,b,c):
    return A.add_f(a,b) + c

B1= B()    
print B1.sum_f(1,2,3)


Traceback (most recent call last):
File "C:/Users/wxu/Documents/test.py", line 10, in <module>
print B1.sum_f(1,2,3)
File "C:/Users/wxu/Documents/test.py", line 7, in sum_f
return A.add_f(a,b) + c
TypeError: unbound method add_f() must be called with A instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)

当我没有 sum_f(self,a,b,c) 的 self 时,它给了我这个错误:

Traceback (most recent call last):
File "C:/Users/wxu/Documents/test.py", line 10, in <module>
print test1.sum_f(1,2,3)
TypeError: sum_f() takes exactly …
Run Code Online (Sandbox Code Playgroud)

python class

2
推荐指数
1
解决办法
3万
查看次数

标签 统计

python ×2

class ×1

collections ×1

function ×1

import ×1

nameerror ×1