Pas*_*ten 7 python operators addition
如何评估+ 5工作(扰流警报:结果是5)?
是不是+通过调用__add__方法来工作?5将在" other"中:
>>> other = 5
>>> x = 1
>>> x.__add__(other)
6
Run Code Online (Sandbox Code Playgroud)
那么允许添加5的"空白"是什么?
void.__add__(5)
另一个线索是:
/ 5
Run Code Online (Sandbox Code Playgroud)
抛出错误:
TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)
在+这种情况下调用一元魔术方法__pos__,而不是__add__:
>>> class A(int):
def __pos__(self):
print '__pos__ called'
return self
...
>>> a = A(5)
>>> +a
__pos__ called
5
>>> +++a
__pos__ called
__pos__ called
__pos__ called
5
Run Code Online (Sandbox Code Playgroud)
蟒仅支持其中4(一元的算术运算)__neg__,__pos__,__abs__,和__invert__,因此SyntaxError与/.请注意,__abs__使用内置函数调用abs(),即没有这个一元操作的运算符.
请注意,/5(仅/后面的内容)仅由IPython shell进行不同的解释,对于普通shell,它是预期的语法错误:
Ashwinis-MacBook-Pro:py ashwini$ ipy
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
Type "copyright", "credits" or "license" for more information.
IPython 3.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
>>> /5
Traceback (most recent call last):
File "<ipython-input-1-2b14d13c234b>", line 1, in <module>
5()
TypeError: 'int' object is not callable
>>> /float 1
1.0
>>> /sum (1 2 3 4 5)
15
Run Code Online (Sandbox Code Playgroud)
Ashwinis-MacBook-Pro:~ ashwini$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> /5
File "<stdin>", line 1
/5
^
SyntaxError: invalid syntax
>>> /float 1
File "<stdin>", line 1
/float 1
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |