Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Method with and without Parentheses in Python [duplicate]

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
like image 356
bcf Avatar asked Jul 06 '26 13:07

bcf


1 Answers

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

like image 185
Ignacio Vazquez-Abrams Avatar answered Jul 08 '26 03:07

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!