Linux 如何使用 python file.py 从命令行运行类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20531916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run class from command line using python file.py?
提问by user2611836
when i run python filename.py, it does not prompt for input or print the output. What command do I have to run to run the class Base1()?
当我运行 python filename.py 时,它不会提示输入或打印输出。我必须运行什么命令才能运行 Base1() 类?
class Base(TestCase):
def setUp(self):
#prompts for inpt
......
class Base1(Base):
def base1(self):
print('.......')
return x
def base2(self):
output = Base1.base1(self)
print(output)
回答by Tim Pierce
Your program must include some statements at the top level (i.e. not indented) that will be executed when your program is run on the command line.
您的程序必须包含一些顶级语句(即不缩进),当您的程序在命令行上运行时,这些语句将被执行。
class Base(TestCase):
def setUp(self):
#prompts for inpt
......
class Base1(Base):
def base1(self):
print('.......')
return x
def base2(self):
output = Base1.base1(self)
print(output)
# These commands will be executed when "python filename.py" is run from a shell
foo = Base1()
foo.base1()
....
回答by Coulter Watson
What qwrrty suggested will work, but I would suggest putting it in a main function which in python is done by
qwrrty 建议的内容会起作用,但我建议将它放在一个主要函数中,该函数在 python 中由
def main():
foo = Base1()
foo.base1()
if __name__ == "__main__":
main()