Python class return true

Python __bool__

Summary: in this tutorial, you will learn how to implement the Python __bool__ method to return boolean values for objects of a custom class.

Introduction to the Python __bool__ method

An object of a custom class is associated with a boolean value. By default, it evaluates to True . For example:

class Person: def __init__(self, name, age): self.name = name self.age = age if __name__ == '__main__': person = Person('John', 25)Code language: Python (python)

In this example, we define the Person class, instantiate an object, and show its boolean value. As expected, the person object is True .

To override this default behavior, you implement the __bool__ special method. The __bool__ method must return a boolean value, True or False .

For example, suppose that you want the person object to evaluate False if the age of a person is under 18 or above 65:

class Person: def __init__(self, name, age): self.name = name self.age = age def __bool__(self): if self.age < 18 or self.age > 65: return False return True if __name__ == '__main__': person = Person('Jane', 16) print(bool(person)) # FalseCode language: Python (python)

In this example, the __bool__ method returns False if the age is less than 18 or greater than 65. Otherwise, it returns True . The person object has the age value of 16 therefore it returns False in this case.

Читайте также:  Pdf python standard library

The __len__ method

If a custom class doesn’t have the __bool__ method, Python will look for the __len__() method. If the __len__ is zero, the object is False . Otherwise, it’s True .

If a class doesn’t implement the __bool__ and __len__ methods, the objects of the class will evaluate to True .

The following defines a Payroll class that doesn’t implement __bool__ but the __len__ method:

class Payroll: def __init__(self, length): self.length = length def __len__(self): print('len was called. ') return self.length if __name__ == '__main__': payroll = Payroll(0) print(bool(payroll)) # False payroll.length = 10 print(bool(payroll)) # TrueCode language: Python (python)

Since the Payroll class doesn’t override the __bool__ method, Python looks for the __len__ method when evaluating the Payroll’s objects to a boolean value.

In the following example payroll’s __len__ returns 0, which is False :

payroll = Payroll(0) print(bool(payroll)) # FalseCode language: Python (python)

However, the following example __len__ returns 10 which is True :

payroll.length = 10 print(bool(payroll)) # TrueCode language: Python (python)

Summary

  • All objects of custom classes return True by default.
  • Implement the __bool__ method to override the default. The __bool__ method must return either True or False .
  • If a class doesn’t implement the __bool__ method, Python will use the result of the __len__ method. If the class doesn’t implement both methods, the objects will be True by default.

Источник

Yasoob Khalid

In 325+ pages I will help you implement 12 end-to-end projects to enhance your Python knowledge.

Intermediate Python

In this free, open-source, and widely-read book, you will learn some intermediate Python concepts.

Table of contents

Python mind-teaser: Make the function return True

Hi everyone! 👋 I was browsing /r/python and came across this post:

Image

The challenge was easy. Provide such an input that if 1 is added to it, it is the instance of the same object but if 2 is added it is not.

Solution 1: Custom class

The way I personally thought to solve this challenge was this:

def check(x): if x+1 is 1+x: return False if x+2 is not 2+x: return False return True class Test(int): def __add__(self, v): if v == 1: return 0 else: return v print(check(Test())) # output: True 

Let me explain how this works. In Python when we use the + operator Python calls a different dunder method depending on which side of the operator our object is. If our object is on the left side of the operator then __add__ will be called, if it is on the right side then __radd__ will be called.

Our Test object will return 0 if Test() + 1 is called and 1 if 1 + Test() is called. The trick is that we are overloading only one dunder method and keeping the other one same. This will help us pass the first if condition. If you take a second look at it you will see that it helps us pass the second if check as well because we simply return the input if it is not 1 so Test() + 2 will always be similar to 2 + Test() .

However, after reading the comments, I found another solution which did not require a custom class.

Solution 2: A unique integer

User /u/SethGecko11 came up with this absurdly short answer:

def check(x): if x+1 is 1+x: return False if x+2 is not 2+x: return False return True print(check(-7)) # output: True 

Only -7 works. Any other number will not return True. If you are confused as to why this works then you aren’t alone. I had to read the comments to figure out the reasoning.

So apparently, in Python, integers from -5 to 256 are pre-allocated. When you do any operation and the result falls within that range, you get the pre-allocated object. These are singletons so the is operator returns True . However, if you try using integers which don’t fall in this range, you get a new instance.

The memory requirement for pre-allocating these integers is not that high but apparently the performance gains are huge.

So when you use -7 as input, you get a new instance of -6 but the same instance when the answer is -5. This doesn’t work with the upper bound (256) precisely because of the way if statements are constructed. 255 would work as an answer if the check function was implemented like this:

def check(x): if x+1 is not 1+x: return False if x+2 is 2+x: return False return True 

I hope you learned something new in this article. I don’t think you would ever have to use this in any code-base ever but it is a really good mind-teaser which can catch even seasoned Python developers off-guard.

Happy programming! I will see you in the next article 😊

Источник

Функция return в Python

Оператор возврата в python используется для возврата значений из функции. Мы можем использовать оператор return только в функции. Его нельзя использовать вне функции Python.

Функция без оператора возврата

Каждая функция в Python что-то возвращает. Если функция не имеет никакого оператора возврата, она возвращает None.

def print_something(s): print('Printing::', s) output = print_something('Hi') print(f'A function without return statement returns ')

Функция Python без оператора возврата

Пример return

Мы можем выполнить некоторую операцию в функции и вернуть результат вызывающей стороне с помощью оператора return.

def add(x, y): result = x + y return result output = add(5, 4) print(f'Output of add(5, 4) function is ')

Пример оператора Return в Python

return с выражением

У нас могут быть выражения также в операторе return. В этом случае выражение оценивается и возвращается результат.

def add(x, y): return x + y output = add(5, 4) print(f'Output of add(5, 4) function is ')

Заявление о возврате Python с выражением

Логическое значение

Давайте посмотрим на пример, в котором мы вернем логическое значение аргумента функции. Мы будем использовать функцию bool(), чтобы получить логическое значение объекта.

def bool_value(x): return bool(x) print(f'Boolean value returned by bool_value(False) is ') print(f'Boolean value returned by bool_value(True) is ') print(f'Boolean value returned by bool_value("Python") is ')

Логическое значение возврата

Строка

Давайте посмотрим на пример, в котором наша функция вернет строковое представление аргумента. Мы можем использовать функцию str(), чтобы получить строковое представление объекта.

def str_value(s): return str(s) print(f'String value returned by str_value(False) is ') print(f'String value returned by str_value(True) is ') print(f'String value returned by str_value(10) is ')

Строка возврата Python

Кортеж

Иногда нам нужно преобразовать несколько переменных в кортеж. Давайте посмотрим, как написать функцию для возврата кортежа из переменного числа аргументов.

def create_tuple(*args): my_list = [] for arg in args: my_list.append(arg * 10) return tuple(my_list) t = create_tuple(1, 2, 3) print(f'Tuple returned by create_tuple(1,2,3) is ')

Кортеж возврата функции Python

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

Мы также можем вернуть функцию из оператора return. Это похоже на Currying, которое представляет собой метод перевода оценки функции, которая принимает несколько аргументов, в оценку последовательности функций, каждая из которых имеет один аргумент.

def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is ') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is ')

Функция возврата Python

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

Мы также можем вернуть функцию, которая определена вне функции, с помощью оператора return.

def outer(x): return x * 10 def my_func(): return outer output_function = my_func() print(type(output_function)) output = output_function(5) print(f'Output is ')

Возврат внешней функции

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

Если вы хотите вернуть несколько значений из функции, вы можете вернуть объект кортежа, списка или словаря в соответствии с вашими требованиями.

Однако, если вам нужно вернуть огромное количество значений, то использование последовательности – это слишком большая операция по перегрузке ресурсов. В этом случае мы можем использовать yield, чтобы возвращать несколько значений одно за другим.

def multiply_by_five(*args): for arg in args: yield arg * 5 a = multiply_by_five(4, 5, 6, 8) print(a) # showing the values for i in a: print(i)

Возврат против доходности

Резюме

Оператор return в python используется для возврата вывода из функции. Мы узнали, что мы также можем вернуть функцию из другой функции. Кроме того, выражения оцениваются, а затем функция возвращает результат.

Источник

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