Các +
trong trường hợp này gọi phương thức unary diệu __pos__
hơn __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
Python chỉ hỗ trợ 4 (phép tính số học unary) trong số họ __neg__
, __pos__
, __abs__
, và __invert__
, vì thế mà SyntaxError
với /
. Lưu ý rằng __abs__
hoạt động với chức năng tích hợp được gọi là abs()
, nghĩa là không có toán tử nào cho hoạt động đơn nhất này.
Lưu ý rằng /5
(/
tiếp theo một cái gì đó) được hiểu khác nhau bởi IPython vỏ mà thôi, cho vỏ bình thường nó là một lỗi cú pháp như mong đợi:
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
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
Nguồn
2015-05-24 10:14:30
'LoạiError' thứ hai phải làm với tính năng tự động ngoặc đơn IPython, nó thay thế'/whatever' bằng 'whatever()'. Python không có toán tử '/' đơn nhất. – bereal
@bereal Bất kỳ liên kết nào đến tính năng này? Nó không chỉ là dấu ngoặc đơn tự động: '/ sum (1 2 3 4 5)' trả về 15. –
@AshwiniChaudhary được mô tả [ở đây] (https://ipython.org/ipython-doc/dev/interactive/reference.html # automatic-parentheses-and-quotes), (giống như IPython's '?' -help). Rõ ràng, nó cao hơn một chút, hơn được mô tả, ví dụ, '/ 'abc'' trả về'' abc'', tôi không biết nó có nghĩa là gì. – bereal