无法重用以前的类型的值,而不是无

我已经在python中创建了一个函数来通过它打印一些信息。我正在尝试向函数提供list of alphabets以及这些字母所属的type

由于我没有从函数的外部提供type的值,因此将其定义为“无”。但是,当我执行该函数时,它将检查类型的值是否为None。如果为None,它将执行except块以获取一个。

尽管在向该函数提供字母时类型的值是None,但内存中还没有存储先前类型的值(当运行两次时)。

我尝试过:

def get_info(alpha,alpha_type):

    print("checking value of item:",alpha_type)

    try:
        if not alpha_type:raise
        return alpha,alpha_type
    except Exception:
        alpha_type = "vowel"
        return get_info(alpha,alpha_type)

if __name__ == '__main__':
    for elem in ["a","e","o"]:
        print(get_info(elem,alpha_type=None))

它产生的输出:

checking value of item: None
checking value of item: vowel
('a','vowel')
checking value of item: None
checking value of item: vowel
('e','vowel')
checking value of item: None
checking value of item: vowel
('o','vowel')

我希望得到的输出:

checking value of item: None
checking value of item: vowel
('a','vowel')
checking value of item: vowel
('e','vowel')
checking value of item: vowel
('o','vowel')
  

如何重用以前的类型的值而不是无?

顺便说一句,我正在寻求可以保持现有设计完整的解决方案。

xiaoyan198607 回答:无法重用以前的类型的值,而不是无

当前,您每次都是从主要alpha_type=None进行传递。如果您想传递最后一个返回的值,则将main更改为:

if __name__ == '__main__':
    main_type = None
    for elem in ["a","e","o"]:
        result = get_info(elem,alpha_type=main_type)
        main_type = result[1]
        print(result)

输出:

checking value of item: None
checking value of item: vowel
('a','vowel')
checking value of item: vowel
('e','vowel')
checking value of item: vowel
('o','vowel')
本文链接:https://www.f2er.com/3129801.html

大家都在问