Method or function, which is better?

In [136]: a = np.array((1,2,3))

In [137]: a
Out[137]: array([1, 2, 3])

In [138]: np.mean(a)
Out[138]: 2.0

In [139]: a.mean()
Out[139]: 2.0

Here I used ‘mean’ as a method and a function. Are the approaches essentially identical?

Here a is just a pointer to the object array that you created. So, np.mean(a) and a.mean() are technically the same.

By the way, in Python, method implies a function defined inside a class, whereas a function is not.

1 Like

I’ve no idea what you mean by this (pun intended), but np.mean is a module-level function, while a.mean is a method. It so happens that numpy arrays are designed to make these two behave identically, but there is a syntactic and semantic difference here.

But since they ARE equivalent in this circumstance, you can choose whichever you prefer.

1 Like

Yes, here, in both instances, the numpy library mean function (method) is basically acting on the same numpy array object.

So, whether it be np.mean(a) or a.mean(), they’re both referencing the same array and applying the same algorithm to the array (mean method/function).

type(np.mean(a))
<class 'numpy.float64'>

type(a.mean())
<class 'numpy.float64'>

(same results)

From Learning Python, 5th Ed:
sameReferenceObject

Here is just an image highlighting the principle of multiple variables (or pointers to the same object)
referencing the same object. The takeaway here is that the same algorithm is acting upon the same
object (numpy array), regardless of how the object is being referenced. This is the way that I had
interpreted it.

1 Like