当引用我用 'distribution' 制作和安装的包时,我在 python 中得到 'Name is not defined'

I'm getting 'Name is not defined' in python when referencing a package I made and installed with 'distribution'

我正在尝试测试打包脚本并安装它们以备将来使用。我创建了一个脚本 'my_script.py' 然后用 python docs\setup.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 "bin\test2.py", line 5, in <module>
    test_print(self, tool)
NameError: name 'test_print' is not defined

我做错了什么?

定义test_print是来自测试class的方法。所以你必须在使用它之前实例化一个对象:

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)