Everything is object in Python

Everthing is object in run time.

Every object has value, type, base classes, unique id, and attributes.

We can create more objects by calling other callable objects

More on this.

In [1]:
import sys
len
Out[1]:
<function len(obj, /)>

Above, the built-in string function is an object. This object is an callble object. To check if an object is callable, we can use function callable.

In [5]:
callable(len)
Out[5]:
True

What about "callable", must be an callable object?

In [7]:
callable
Out[7]:
<function callable(obj, /)>
In [8]:
callable(callable)
Out[8]:
True
In [11]:
callable(True)
Out[11]:
False

Note the object True is not an callable object. We cannot do True().

In [12]:
True()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-dffdaf8f3427> in <module>
----> 1 True()

TypeError: 'bool' object is not callable
In [ ]:
The function objects have dunder format of calling them. See below:
In [9]:
"string".__len__
Out[9]:
<method-wrapper '__len__' of str object at 0x7fbf5ea85fb0>
In [10]:
"string".__len__()
Out[10]:
6

You can try yourself with all the datatypes and values to see if they are objects. The type objects return empty object instance of that type. Check the below:

In [13]:
str()
Out[13]:
''
In [14]:
int()
Out[14]:
0
In [15]:
dict()
Out[15]:
{}

Since numbers are also object, we can do the addition this way too:

In [18]:
5.67.__add__
Out[18]:
<method-wrapper '__add__' of float object at 0x7fbf61b596b0>
In [21]:
callable(5.67.__add__)
Out[21]:
True
In [19]:
5.67.__add__()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-449950c1d188> in <module>
----> 1 5.67.__add__()

TypeError: expected 1 arguments, got 0
In [20]:
5.67.__add__(2)
Out[20]:
7.67

We can get the size of the objects in bytes using sys.getsizeof() function.

In [22]:
sys.getsizeof('a')
Out[22]:
50
In [23]:
sys.getsizeof('abcd')
Out[23]:
53

Above, since the values are stored in the objects, the size of 'abcd' is just three bytes more than size of 'a' which is 50 bytes. More examples:

In [24]:
sys.getsizeof(1)
Out[24]:
28
In [25]:
sys.getsizeof(2**30-1)
Out[25]:
28
In [26]:
sys.getsizeof(2**30)
Out[26]:
32

Reference: Stuart Williams - Python Epiphanies - PyCon 2018 https://www.youtube.com/watch?v=-kqZtZj4Ky0&t=498s