用类和函数在命令行中调试Python

2024-09-28 23:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我对linux中的python脚本以及在终端中执行它们是相当陌生的。我试着调试一些相互交互的脚本,但是我不知道如何在命令行中访问脚本的某些部分。下面是我正在练习的一个测试脚本示例。你知道吗

文件名为:

test.py

脚本是:

class testClass():

    def __init__(self, test):

        self.test = test

    def testing():

        print "this wont print"


def testing2():

   print "but this works"

在终端中,如果我转到文件所在的文件夹并尝试打印testing()函数

python -c 'import test; print test.testClass.testing()'

我听到一个错误说

Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: unbound method testing() must be called with testClass instance  as first argument (got nothing instead)

但是如果我尝试打印testing2()函数

python -c 'import test; print test.testing2()'

它会打印“但是这个有用”

如何执行testing()函数使其打印出来。我试过把各种各样的论点放进去,但都没用。你知道吗

谢谢


Tags: 函数命令行testimportself脚本终端linux
1条回答
网友
1楼 · 发布于 2024-09-28 23:12:10

你的课程应该是:

class testClass():
    def __init__(self, test):
        self.test = test

    def testing(self):
        print "this wont print"

需要使用testClass的实例调用该方法:

test.testClass("abc").testing()

其中"abc"表示test__init__参数。或:

t = test.testClass("abc")
test.testClass.testing(t)

作为shell命令:

python -c 'import test; print test.testClass("abc").testing()'

有关详细信息,请参见Difference between a method and a functionWhat is the purpose of self?。你知道吗

相关问题 更多 >