An Interesting Python Function
如何让下面这个函数返回 True
?
1def check(x):
2 if x+1 is 1+x:
3 return False
4 if x+2 is not 2+x:
5 return True
解法1: 自定义类
1def check(x):
2 if x+1 is 1+x:
3 return False
4 if x+2 is not 2+x:
5 return False
6 return True
7
8class Test(int):
9 def __add__(self, v):
10 if v == 1:
11 return 0
12 else:
13 return v
14
15print(check(Test()))
16# output: True
如果一个对象是在 +
的左侧,那会调用 __add__
,如果在右侧,会调用 __radd__
。上面的 Test
类继承自 int,重写了其中的 __add__
方法,但是保留了 __radd__
,所以上面的例子里面, Test()+1
会返回 0, 1+test()
会返回 1。 Test()+2
会返回 2, 2+Test()
也会返回 2。
解法2:特殊的整数
1def check(x):
2 if x+1 is 1+x:
3 return False
4 if x+2 is not 2+x:
5 return False
6 return True
7
8print(check(-7))
9# output: True
只有 -7
可以。python 里面对于 -5 - 256
这些整数会提前生成,这些都是单例。所以 -7+1 is 1-7
是 False
,以及 -7+2 is not 2-7
是 False
,两个 if 条件都不成立。