Python class return object

How does return() in Python work?

In order to get a value from a function in any programming language, we use the return() statement. Likewise, in Python, the return() statement is used to exit a function and returns a value from a function. In this tutorial, we will read about various ways to use the return() statements in Python.

Table of contents

  1. Introduction to return() statement
  2. Returning Multiple Values in Python
  3. Argument in return() function
  4. Function returning another function
  5. Closing thoughts

return() in Python

The return() statement, like in other programming languages ends the function call and returns the result to the caller. It is a key component in any function or method in a code which includes the return keyword and the value that is to be returned after that.
Some points to remember while using return():

  • The statements after the return() statement are not executed.
  • return() statement can not be used outside the function.
  • If the return() statement is without any expression, then the NONE value is returned.

Syntax of return() in Python:

 def func_name(): statements. return [expression] 

Using a return() statement for returning multiple values in Python

Python also gives an option to return multiple values from a function and in order to do that the user just needs to add multiple return values separated by commas. Also known as a tuple, can be created with or without using the ().

Input:

 def statFun(a, b): difference = a-b percent_diff = (difference/a)*100 return difference, percent_diff; difference, percent_diff = statFun() print (difference) print (percent_diff) 

Here, the function statFun() gives to values and by using tuple we return both of the values.

Output:

return() in Python with an argument

In Python, arguments can be used with a return statement. To begin with, arguments are the parameter given by the user and as we know, the argument is the value(s) as input, which is given by the user to the function.

Читайте также:  Программы на java таймер

Input:

 def divNum(a, b): if b != 0 return a/b; else: return 0; print (divNum(4, 2)) print (divNum(2, 0)) 

Here, the function divNum() accepts two arguments and if the second argument is non zero it divides them otherwise returns 0.

Output:

Function returning another function in Python

As we know functions are treated as first-class objects in Python, therefore we can return a function from another function. A first-class object is an object that can be assigned to a variable, passed as an argument to a function, or used as a return value in a function.
A function that takes a function as an argument, returns a function as a result, or both is known as a higher-order function.

Input:

 def func_1(a): def func_2(b): return a-b return func_2 x = func_1(100) print ("The value of a-b is", x(50)) def another_func(a): return a*10 def func(): return another_func y = func() print ("\nThe value of a*b is" y(10)) 

Output:

 The value of a-b is 50 The value of a*b is 100 

Closing thoughts

The return statement sends any object from the function back to the caller code. Since the return statement is a key part of any function or method, if you learn how to use it correctly, you can move to complex codes. One can learn about more Python concepts here.

Источник

Python class return object

Last updated: Feb 22, 2023
Reading time · 2 min

banner

# Purpose of ‘return self’ from a class method in Python

The purposes of the return self statement from a class method are:

  1. The ability to chain multiple calls to a method because return self returns the instance object.
  2. Using the iterator protocol, which requires us to return self from the __iter__() method.
Copied!
class Calc(): def __init__(self, number=0): self.number = number def add(self, value): self.number = self.number + value return self def subtract(self, value): self.number = self.number - value return self calc = Calc() calc.add(5).subtract(2).add(5) print(calc.number) # 👉️ 8 calc.subtract(5).add(3) print(calc.number) # 👉️ 6

purpose of return self in class method

The add and subtract methods in the Calc() class use a return self statement.

When we call an instance method, Python automatically passes self as the first argument to the method.

self represents an instance of the class — the instance on which the method was called.

When we return self from a class method, we basically return the instance object.

Читайте также:  Datetime python django model

This allows us to chain multiple calls to the method in a single statement.

# Chaining multiple calls to a method that returns self

The add() and subtract() methods return the instance, so we can chain many calls to the methods in a single line, without storing the results in intermediary variables.

Copied!
class Calc(): def __init__(self, number=0): self.number = number def add(self, value): self.number = self.number + value return self def subtract(self, value): self.number = self.number - value return self calc = Calc() calc.add(5).subtract(2).add(5) print(calc.number) # 👉️ 8

chaining multiple calls to method that returns self

You aren’t going to see the pattern of method chaining often, but some libraries make use of it.

The idea is that each method returns an object, which allows the calls to be chained together in a single statement without storing the results in intermediary variables.

When you see syntax such as obj.a().a().b() , the code under the hood uses the method chaining pattern.

However, returning self from class methods is much more common when implementing the iterator protocol.

The _ _ iter _ _ () method must return the iterator object itself.

Here is an example of how to make a class iterable by implementing the __iter__() method.

Copied!
class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): # 👇️ return `self` here return self def __next__(self): self.current += 1 if self.current self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3

making a class iterable

The __iter__() method is implicitly called at the start of loops and returns the iterator object ( self ).

The __next__() method is implicitly called at each loop increment and returns the next value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оператор return в Python: возврат значений из функции

Оператор return в Python используется для возврата значения из функции. Пользователь может использовать оператор возврата только в функции. Его нельзя использовать вне функции Python. Оператор возврата включает ключевое слово return и значение, которое будет возвращено после этого.

Синтаксис оператора возврата:

def funtion_name(): statements . . . return [expression]
def adding(x, y): i = x + y return i result = adding(16, 25) print(f'Output of adding(16, 25) function is ')

Программа 1

def adding(a, b): # this function is return the value of(a + b) return a + b def boolean_function(a): # this function is return the Boolean value return bool(a) # calling function flag = adding(2, 3) print("Output of first function is <>".format(flag)) flag = boolean_function(9 < 5) print("\nOutput of second function is <>".format(flag))

Программа 2

Возврат нескольких значений

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

1. Использование объекта: этот метод похож на C / C ++ и Java. Пользователь может создать класс для хранения нескольких значений в функции и возврата объекта этого класса.

class a: def __init__(self): self.omg = "javatpoint is the best website to learn" self.i = 122 # This function will return an object of the class a def test(): return a() # Driver code to test the above method z = test() print(z.omg) print(z.i)

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

2. Использование кортежа: кортеж похож на список, но есть небольшая разница между кортежем и списком. В кортеже значения объекта нельзя изменить, а в списке – можно.

def test(): omg = "javatpoint is the best website to learn" i = 122 return omg, i; # Return tuple, we could also. # Driver code to test the above method. omg, i = test() # Assign return tuple print(omg) print(i)

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

3. Использование списка: список аналогичен массиву динамического размера. В списке пользователь может хранить все в одной переменной.

def test(): omg = "javatpoint" i = 122 return [omg, i]; # Driver code to test the above method list = test() print(list)

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

4. Использование словаря. В языке Python словарь – это набор неструктурированных элементов, которые используются для хранения значений данных, таких как хэш или карта.

def test(): a = dict(); a['omg'] = "javatpoint" a['i'] = 122 return a # Driver code to test the above method a = test() print(a)

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

5. Использование класса данных(Python 3.7+)

from dataclasses import dataclass @dataclass class Book_list: bookname: str cost: float quantity_of_book_available: int = 0 # This function is used to calculate the total cost of the books def total_cost_of_book(self) -> float: return self.cost * self.quantity_of_book_available book = Book_list("Python programming language.", 499, 10) i = book.total_cost_of_book() # print the total cost print(i) # print the details of the book print(book)

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

Функция, возвращающая другую функцию

В языке программирования Python функция имеет форму объекта. Следовательно, пользователь может вернуть функцию из другой функции.

В приведенной ниже программе функция first_add возвращает функцию second_add.

def first_add(x): def second_add(y): return x + y return second_add i = first_add(20) print("The value of x + y is", i(10)) # second function def outer_func(x): return x * 5 def func(): # return the value in the different function return outer_func # storing the function in z z = func() print("\nThe value of x * y is", z(10))

Источник

Оцените статью