在Python中使用带括号和不带括号的方法调用

4

我意识到某些方法应该使用()调用,而其他方法则不能。我如何通过IPython等工具检查是否需要使用括号?例如下面的文件scratch.py

import numpy as np

arr = np.random.randn(5)

print arr.sort, "\n"
print arr.sort(), "\n";
print arr.shape, "\n";
print arr.shape(), "\n";

生成以下输出:

<built-in method sort of numpy.ndarray object at 0x7fb4b5312300> 

None 

(5,) 

Traceback (most recent call last):
  File "scratch.py", line 8, in <module>
    print arr.shape(), "\n";
TypeError: 'tuple' object is not callable
2个回答

6
那些不是方法,而是属性。Python本身会在后台调用描述符

或者它们可能只是属性。 - BrenBarn

2

Python中的方法总是使用()调用。 检查某个东西是否为方法的最佳方法是阅读库的文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接