Calling Method with and without Parentheses in Python

若如初见. 提交于 2019-12-07 13:18:47

问题


I've realized that some methods should be called with (), while others can't. How can I check, using IPython e.g., whether to use parentheses or not? For example the following file 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";

produces this output:

<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

回答1:


Those are not methods, those are properties. The descriptor is invoked behind the scenes by Python itself.




回答2:


Methods in Python are always invoked with a (). Best way to check if something is a method is to read the documentation of the library.



来源:https://stackoverflow.com/questions/36512118/calling-method-with-and-without-parentheses-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!