Python中带括号和不带括号的调用方法 [英] Calling Method with and without Parentheses in Python

查看:54
本文介绍了Python中带括号和不带括号的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到有些方法应该用 () 调用,而其他方法则不能.如何使用 IPython 检查,例如是否使用括号?例如下面的文件 scratch.py​​

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";

产生这个输出:

<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

推荐答案

那些不是方法,那些是 属性.descriptor 由 Python 本身在幕后调用.

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

这篇关于Python中带括号和不带括号的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆