3

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_()?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Leon
  • 61
  • 5
  • 2
    Here, `size` isn't a method/function, but rather an *attribute*, so no parens are needed as it's not being "called". (I realize it may be a descriptor, but that's certainly outside the scope). A more complete answer may actually explain that both `size` and `var` are being looked up similarly, and then `var` is being called. – jedwards Jun 09 '18 at 11:40
  • `np.round_(..)` because the method you are calling belongs to `np` - not to the ndarray `a` - you do not need to memorize them, you can look them up: https://docs.scipy.org/doc/numpy-1.13.0/reference/ - methods need () , properties do not. – Patrick Artner Jun 09 '18 at 11:42

2 Answers2

4

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.

ted
  • 13,596
  • 9
  • 65
  • 107
2

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350