Возврат нескольких значений в функциях Python

В Python мы можем возвращать несколько значений из функции. Ниже приведены различные способы

Использование объекта (object)

Это похоже на C/C++ и Java, мы можем создать класс (в C, структуру) для хранения нескольких значений и возврата объекта класса.

# A Python program to return multiple 
# values from a method using class
class Test:
    def __init__(self):
        self.str = "string example"
        self.x = 20   
  
# This function returns an object of Test
def fun():
    return Test()
      
# Driver code to test above method
t = fun() 
print(t.str)
print(t.x)

Результат работы кода:

string example
20

Использование кортежа (tuple)

Кортеж представляет собой последовательность элементов, разделенных запятыми. Он создается с или без (). Кортежи неизменны.

# A Python program to return multiple 
# values from a method using tuple
  
# This function returns a tuple
def fun():
    str = "string example"
    x   = 20
    return str, x;  # Return tuple, we could also
                    # write (str, x)
  
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)

Результат работы кода:

string example
20

Использование списка (list)

Список похож на массив элементов, созданный с помощью квадратных скобок. Они отличаются от массивов тем, что могут содержать элементы разных типов. Списки отличаются от кортежей тем, что они изменяемы.

# A Python program to return multiple 
# values from a method using list
  
# This function returns a list
def fun():
    str = "string example"
    x = 20   
    return [str, x];  
  
# Driver code to test above method
list = fun() 
print(list)

Результат работы кода:

['string example', 20]

Использование словаря (dictionary)

Словарь похож на хэш или карту на других языках.

# A Python program to return multiple 
# values from a method using dictionary
  
# This function returns a dictionary
def fun():
    d = dict(); 
    d['str'] = "string example"
    d['x']   = 20
    return d
  
# Driver code to test above method
d = fun() 
print(d)

Результат работы кода:

{'x': 20, 'str': 'string example'}

Использование класса данных (Data Class)

В Python 3.7 и более поздних версиях класс данных можно использовать для возврата класса с автоматически добавленными уникальными методами. Модуль класса данных имеет декоратор и функции для автоматического добавления сгенерированных специальных методов, таких как __init__() и __repr__() в пользовательские классы.

from dataclasses import dataclass
  
@dataclass
class Book_list:
    name: str
    perunit_cost: float
    quantity_available: int = 0
          
    # function to calculate total cost    
    def total_cost(self) -> float:
        return self.perunit_cost * self.quantity_available
      
book = Book_list("Introduction to programming.", 300, 3)
x = book.total_cost()
  
# print the total cost
# of the book
print(x)
  
# print book details
print(book)
  
# 900
Book_list(name='Python programming.',
          perunit_cost=200,
          quantity_available=3)

Результат работы кода:

900
Book_list(name='Introduction to programming.', perunit_cost=300, quantity_available=3)
Book_list(name='Python programming.', perunit_cost=200, quantity_available=3)
5 1 голос
Рейтинг статьи
Шамаев Иван
Разработчик аналитических решений QlikView/Qlik Sense/Power BI; Python Data Scientist; Разработчик интеграционных решений на PHP, Python, JavaScript.
0
Оставьте комментарий! Напишите, что думаете по поводу статьи.x