直接调用方法并赋值给变量
def my_method():return "Hello, World!"result = my_method()print(result) 输出:Hello, World!
使用元组解包
def my_method_with_multiple_returns():return "Hello", "World!"a, b = my_method_with_multiple_returns()print(a) 输出:Helloprint(b) 输出:World!
使用下划线`_`丢弃不需要的返回值
def my_method_with_multiple_returns():return "Hello", "World!"a, _ = my_method_with_multiple_returns()print(a) 输出:Hello

使用`next`函数获取返回值
def my_generator():yield "Hello"yield "World!"gen = my_generator()print(next(gen)) 输出:Helloprint(next(gen)) 输出:World!
使用`return`语句
def my_function():return "Hello, World!"print(my_function()) 输出:Hello, World!
使用`try-except`语句捕获异常
def my_function_with_exception():return "Hello, World!"try:result = my_function_with_exception()print(result)except Exception as e:print(f"An error occurred: {e}")
以上方法可以帮助你在Python中获取方法的返回值。
