0

Is there any intuition behind why some functions are instance vs. class?

For instance, if I have a DataFrame df and import pandas/Numpy then:

df.head() # works
df.head # doesn't work
pd.head(df) # doesn't work

df.columns # works
df.columns() # doesn't work
pd.columns(df) # doesn't work

Is it pure memorization why the things that work work, and the things that don't work don't work, or is there some intuition?

mnmn
  • 37
  • 4
  • 1
    well, genrally speaking, instance methods *act on instances*. Note, `pd` isn't a class, it is a *module* – juanpa.arrivillaga Aug 17 '22 at 04:55
  • 3
    ¯\\_(ツ)_/¯ Every library is designed differently (and not always consistent with itself) – SuperStormer Aug 17 '22 at 04:56
  • 3
    In any case, the best way to learn how things work is by *reading the documentation* – juanpa.arrivillaga Aug 17 '22 at 04:57
  • 2
    “Instance vs. class” seems to be entirely irrelevant in your examples, it’s just *attribute vs. method*. – deceze Aug 17 '22 at 05:08
  • 1
    As a rule of thumb, which sometimes fails: If you don't need to provide arguments, an attribute is fine (`df.head()` accepts an argument). Sometimes it's not clear if there might be a future need for arguments, so you start out with a method that doesn't need any arguments. That provides better backwards compatibility. – Timus Aug 17 '22 at 07:33
  • In `numpy` often array methods have a module function equivalent. That's not true generally. Keep the documentation handy, either via the web, or your IDE (e.g. `ipython`). – hpaulj Aug 17 '22 at 13:45

1 Answers1

1

As mentioned in the commends, there is no rule and every library can be different. However, here some intuition:

Attributes (or properties) are usually used to access characteristics of an object like its color, name, size - or in your case columns names: df.columns.

Methods are used when some sort of action is involved. For example rotate(), plot(), rename("new name") - or printing the first rows df.head(). Although it is less obvious in this case.

Module functions are used in case the target object is not as clear or multiple objects are involved, e.g. pd.merge(df1, df2).

Have a look at this post on attributes and methods.

kjanker
  • 71
  • 3