【问题标题】:I'm getting 'Name is not defined' in python when referencing a package I made and installed with 'distribution'引用我制作并使用“分发”安装的包时,我在 python 中得到“名称未定义”
【发布时间】:2018-05-25 20:07:32
【问题描述】:

我正在尝试测试打包脚本并安装它们以备将来使用。我创建了一个脚本'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().test_print(tool)test_print 是类test 的实例方法。你也没有通过self 争论,它只在课堂上使用。

标签: python python-2.7 class package distribute


【解决方案1】:

定义 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)

【讨论】:

  • 谢谢你,这很有意义,而且很有魅力!
猜你喜欢
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2015-03-24
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多