-1

Suppose we have

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

for checking the type of a, we used this function

type(a)

to check the type of attribute, we used this

a.dtype

Why in the first case we used type(a) and in the second case we used a.dtype and why not dtype(a) I have seen this many times in other libraries too. Kindly explain me the basics of it.

Joseph arasta
  • 161
  • 1
  • 3
  • 12
  • 1
    We use dot notation to access _properties_ of objects (e.g. `a.dtype` accesses the property `dtype` of the object `a`). If those properties (or any object) happen to also be functions, we can _call_ them with the parentheses (`np.array([1, 2, 3])` calls the function `np.array` with the argument `[1, 2, 3]`) – Green Cloak Guy May 24 '21 at 04:24
  • bcz `dtype` is an attribute and `type()` is a method – Anurag Dabas May 24 '21 at 04:25
  • 1
    @GreenCloakGuy exactly so, except swap every use of the word "property" with "attribute." (A property is a specific _type_ of attribute) – Adam Smith May 24 '21 at 04:26
  • The obvious reason why we sometimes use method-call syntax and sometimes function-call syntax, is that some things are methods and other are functions. [This stack overflow question](https://stackoverflow.com/questions/237128/why-does-python-code-use-len-function-instead-of-a-length-method) contains some discussion about how that situation came to be. – Ture Pålsson May 24 '21 at 04:37
  • Does that mean, functions which are not in any class, are used like type(a) and whereas if we want to use a function which is in a class, we have to use a.dtype ? Is my understanding correct ? – Joseph arasta May 24 '21 at 05:59
  • 1
    @Anurag `type` is a *function*! – deceze May 24 '21 at 06:46

3 Answers3

2

type(a) is a builtin function that gives the type of the object a

a.dtype is using attribute access to access the attribute dtype of the object a, which in the case of np.array is the type of data contained in a.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

Basically, when you write type(a), you are calling the function type(), which gives the type of its parameter. (You need the () to call the function)
With a.dtype, a is an instance, and dtype is a method in that class. (The "." is there to show the code that the method dtype is in the same class with the instance a)

Here is a useful link that explains it; https://www.codecademy.com/forum_questions/5170307264a7402d9a0012f5

TNT
  • 31
  • 4
0

in case type(a) the a is the parameter for the method also [1,2,3] in a = np.array([1,2,3]) but in case a.dtype, dtype may be a method of class or maybe a function

ELAi
  • 170
  • 2
  • 8