使用 类 和函数在命令行中调试 Python
Debugging Python in command line with classes and functions
我对 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()'
它将打印"but this works"
我将如何执行 testing() 函数以使其打印。我试过在其中放入各种参数,但没有任何效果。
谢谢
您的 class 应该是:
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 function and What is the purpose of self?。
我对 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()'
它将打印"but this works"
我将如何执行 testing() 函数以使其打印。我试过在其中放入各种参数,但没有任何效果。
谢谢
您的 class 应该是:
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 function and What is the purpose of self?。