【问题标题】:function within f-string is returning the function outside the string, and returning None inside the stringf-string 内的函数返回字符串外的函数,并在字符串内返回 None
【发布时间】:2022-01-18 21:20:15
【问题描述】:

我是 python 新手,并尝试按如下方式执行 f-string:

next_patient = East_Room.get_highest_priority()
print(f"The next patient is {next_patient.display_symptoms()} please")

其中 East_Room 是一个类的实例,get_highest_priority 是该类中的一个方法,用于显示具有“严重性”属性的最高整数的患者,如下所示:

def get_highest_priority(self):
    tmp_priority_patient = None
    current_size = self.SLL_waiting_list.size()     
    counter = 1
    while counter <= current_size:
        tmp_node = self.SLL_waiting_list.get_node(counter)
        tmp_patient = tmp_node.get_obj()
        if tmp_priority_patient == None:
            tmp_priority_patient = tmp_patient
        else:
            if tmp_patient.severity > tmp_priority_patient.severity:
                tmp_priority_patient = tmp_patient
        counter = counter + 1
    return tmp_priority_patient

def display_symptoms(self):
print(f"{self.firstname} {self.lastname}:{self.symptoms}")

这是输出:

康纳:拿索

请下一位患者是无

我知道如果我在没有 f 字符串的情况下调用它,这个方法可以完美运行。谢谢你的帮助!

【问题讨论】:

  • 你能告诉我们display_symptoms函数吗?看起来问题来自那里。
  • “我知道这个方法可以正常工作,因为如果我在没有 f 字符串的情况下调用它,它就可以完美运行”。说服我们。不清楚为什么会这样。
  • 我们只知道它有效。您在此处显示的任何内容都没有表明它应该这样做。我们需要一个minimal reproducible example
  • @dylan193 请编辑您的问题以添加display_symptoms的代码
  • @AdamBoinet 是的,现在可以正常工作了。谢谢!只是想知道,为什么该函数在 f 字符串之外工作?因为它打印出来但没有返回值?

标签: python oop


【解决方案1】:

display_symptoms 只打印信息,不返回任何内容。

在 Python 中,不返回任何内容的函数返回 None,因此您得到的输出是:“请下一位患者为无”

如果您还希望函数返回此字符串,则必须显式返回它:

def display_symptoms(self):
    print(f"{self.firstname} {self.lastname}: {self.symptoms}")
    return f"{self.firstname} {self.lastname}: {self.symptoms}"

一个更好的方法是让它成为一个属性:

@property
def display_symptoms(self):
    return f"{self.firstname} {self.lastname}: {self.symptoms}"

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2020-04-30
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多