Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

and operation overloading in python

Tags:

python

I know logically and is used for booleans evaluating to true if both the conditions are true, but I have a problem with the following statement:

print "ashish" and "sahil"

it prints out "sahil"?
 another example:
 return s[0] == s[-1] and checker(s[1:-1])
 (taken from recursive function for palindrome string
 checking            
please explain it and other ways and is oveloaded ,especially what the second statement do.
like image 689
user2688772 Avatar asked Sep 05 '13 19:09

user2688772


People also ask

What is operator overloading in Python?

This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.

Why ‘+’ operator is overloaded in C++?

It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading .

How to modify the operation of an operator in Python?

Python gives us the ability to modify the operation of an operator when used for specific operands. Every time we use an operator, Python internally invokes a magic method. In the case of +, Python invokes the __add__ method. We can redefine this method in our object’s class to create a custom operation for the + operator.

How to do the addition operation in Python?

Now let's try the addition operation again: What actually happens is that, when you use p1 + p2, Python calls p1.__add__ (p2) which in turn is Point.__add__ (p1,p2). After this, the addition operation is carried out the way we specified.


2 Answers

and is not overloaded.

In your code, "ashish" is a truthy value (because non-empty strings are truthy), so it evaluates "sahil". As "sahil" is also a truthy value, "sahil" is returned to the print statement and is then printed.

like image 193
Matt Bryant Avatar answered Nov 09 '22 23:11

Matt Bryant


x and y basically means:

return y, unless x is False-ish - in such case return x

Here is a list of possible combinations:

>>> from itertools import combinations
>>> items = [True, False, 0, 1, 2, '', 'yes', 'no']
>>> for a, b in combinations(items, 2):
    print '%r and %r => %r' % (a, b, a and b)


True and False => False
True and 0 => 0
True and 1 => 1
True and 2 => 2
True and '' => ''
True and 'yes' => 'yes'
True and 'no' => 'no'
False and 0 => False
False and 1 => False
False and 2 => False
False and '' => False
False and 'yes' => False
False and 'no' => False
0 and 1 => 0
0 and 2 => 0
0 and '' => 0
0 and 'yes' => 0
0 and 'no' => 0
1 and 2 => 2
1 and '' => ''
1 and 'yes' => 'yes'
1 and 'no' => 'no'
2 and '' => ''
2 and 'yes' => 'yes'
2 and 'no' => 'no'
'' and 'yes' => ''
'' and 'no' => ''
'yes' and 'no' => 'no'
like image 33
Tadeck Avatar answered Nov 09 '22 23:11

Tadeck