Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions in Python with or without parentheses? [duplicate]

In Python, there are functions that need parentheses and some that don't, e.g. consider the following example:

a = numpy.arange(10)
print(a.size)
print(a.var())

Why does the size function not need to be written with parentheses, as opposed to the variance function? Is there a general scheme behind this or do you just have to memorize it for every function?

Also, there are functions that are written before the argument (as opposed to the examples above), like

a = numpy.arange(10)
print(np.round_(a))

Why not write a.round_ or a.round_()?

like image 675
Leon Avatar asked Aug 23 '26 01:08

Leon


2 Answers

It sounds like you're confused with 3 distinct concepts, which are not specific to python, rather to (object oriented) programming.

  • attributes are values, characteristics of an object. Like array.shape
  • methods are functions an object can run, actions it can perform. array.mean()
  • static methods are functions which are inherent to a class of objects, but don't need an object to be executed like np.round_()

It sounds like you should look into OOP: here is a python primer on methods.


Also, a more pythonic and specific kind of attributes are propertys. They are methods (of an object) which are not called with (). Sounds a bit weird but can be useful; look into it.

like image 178
ted Avatar answered Aug 25 '26 13:08

ted


arrange returns an ndarray. size isn't a function, it's just an attribute of the ndarray class. Since it's just a value, not a callable, it doesn't take parenthesis.

like image 31
Mureinik Avatar answered Aug 25 '26 14:08

Mureinik



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!