我在引用我制作并使用"发行版"安装的软件包时在 python 中得到"名称未定义"



我正在尝试测试包装脚本并安装它们以备将来使用。我创建了一个脚本" my_script.py",然后与 python docssetup.py develop似乎有效,因为我得到了所有成功的安装行。此代码包含以下内容:

class test(object):
    def test_print(self, tool):
        for i in tool:
            print i

然后我创建了一个脚本,上面写着:

from my_script import test
tool = (1, 2, 3, 4, 5, 6)
test_print(self, tool)

它正在返回:

Traceback (most recent call last):
  File "bintest2.py", line 5, in <module>
    test_print(self, tool)
NameError: name 'test_print' is not defined

我在做什么错?

定义 test_print 是测试类的方法。因此,您必须在使用之前实例化对象:

from my_script import test
tool = (1, 2, 3, 4, 5, 6)
testObj = test()
testObj.test_print(tool)

否则,也可以添加@staticmethod装饰器以将方法定义为静态。

class test(object):
    @staticmethod
    def test_print(tool):
        for i in tool:
            print i
 from my_script import test
 tool = (1, 2, 3, 4, 5, 6)
 test.test_print(tool)

最新更新