如何从函数或方法返回“pass”?

2024-04-18 14:41:01 发布

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

我创建了一个方法,将一个句子拆分成单词并返回句子的第一个单词(可以使用NLTK tokenizerargparse,但由于这是一个用于学习Python的类项目,因此我从头开始创建了一个简单的标记器)该方法还有一个有用的“help”参数,其中传递-h--help将显示帮助文本。但是,我希望函数输出帮助文本,如果用户通过-h或--help,则输出'break'或'pass'。我的方法是:

class example_method(object):
    def __init__(self):
        self.data = []

    def parse(self, message):
        if(("-h" or "--help") in message): 
            print("This is a helpful message")
        else:
            self.data = [x.strip() for x in message.split(' ')]
            return self.data

如果用户输入一条常规消息,则该方法有效。让我举例说明:

example = example_method()
input_message = "Hello there how are you?"
print(example.parse(input_message)[0])

以上方法效果很好。但是,如果用户输入-h或--help,该方法将返回一个错误:

example = example_method()
input_message = "--help"
print(example.parse(input_message)[0])

以上将返回:TypeError: 'NoneType' object is not subscriptable 我意识到一个可能的解决方案是:

try: print(example.parse(input_message)[0])
except: pass

但是有没有一种方法可以像这样从方法内部返回pass?你知道吗

    def parse(self, message):
        if(("-h" or "--help") in message): 
            print("This is a helpful message")
            return pass
        else:
            self.data = [x.strip() for x in message.split(' ')]
            return self.data

我的目的是,我不想要一个错误消息,因为这个方法是一个更大的程序的一部分,一个错误只会使输出看起来难看。如果该方法输出帮助文本,然后在没有错误的情况下退出,那么看起来会更加专业。你知道吗


Tags: 方法用户in文本selfmessageinputdata
3条回答

也许只需要安排parse函数返回None,然后调用函数就可以检查这种情况并处理它

例如:

class example_method(object):
    # …
    def parse(self, message):
        if message in {"-h", "--help"}:
            print("This is a helpful message")
            return  # implicitly returns None

        self.data = [x.strip() for x in message.split(' ')]
        return self.data

res = example.parse(input_message)
if res is None:
    return

print(res[0])

可以使用exit()立即停止程序执行。你知道吗

def parse(self, message):
    if(("-h" or "--help") in message): 
        print("This is a helpful message")
        exit()
    else:
        self.data = [x.strip() for x in message.split(' ')]
        return self.data

考虑使用^{}来自动生成-h--help标志和帮助文本。你知道吗

低工作量演示:

你知道吗脚本.py你知道吗

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-p', help='This will be printed')
args = parser.parse_args()

print(args.p)

用法:

$ python3 script.py -p hello
hello
$ python3 script.py -h
usage: script.py [-h] [-p P]

optional arguments:
  -h, --help  show this help message and exit
  -p P        This will be printed

如您所见,使用-h(或--help)显示帮助消息,并且不执行任何其他代码(默认情况下)。你知道吗

相关问题 更多 >