what's the link between attribute and method of an object in Python?

时间:2017-04-10 01:26:36

标签: python methods attributes

I am new in Python and I mean the difference of how they are implemented.

For example:

>>> a=np.array([1,2,5,3,43])
>>> a.sort()
>>> a
array([ 1,  2,  3,  5, 43])
>>> a=np.array([1,2,5,3,43])
>>> a.shape
(5,)
>>> a.sort()
>>> a
array([ 1,  2,  3,  5, 43])
>>> a.sort
<built-in method sort of numpy.ndarray object at 0x7f78e358a9e0>
>>> a.shape()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Maybe the answer should be something like the special use of " _ _ foo_ _" in Python

1 个答案:

答案 0 :(得分:1)

A method is a function that is associated with the object. When you type a.sort its returning the address in memory where the function is stored and if you use parenthesis it calls the function. An attribute is just a variable inside your object so when you call a.shape() it gives you an error since you're trying to call a variable as a function.

Not sure if this is what you were looking for but I hope it helped