Fundamentally, python is a interpreter language which is unlike c or c++ which is compiled as well.
Compiler job is to take the high level code and then convert into bytecode which can be executed by the OS
So, what does interpreter do? interpreter takes some code and translates on the fly and execute on the machine. In C, we do the compilation and then run the compiled code in the machine. Whereas, in python, we interpret and execute the code runtime.
Even though python is interpreter language, it is also compiled and converted to bytecode before interpretation is done.
So how does python works?
python code –> translator/compiled is used when we press “run” –> bytecode
the job of the translator is to check the syntax of the python code.
next step is: the bytecode will be interpreted on the fly and translated to machine code which is executed on the machine.
Python Data models
Why below code works ?
In [1]: x = [1,2,3]
In [2]: y = [4,5]
In [7]: x+y
Out[7]: [1, 2, 3, 4, 5]
In [8]: x * 3
Out[8]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
The reason is the python data models which represents various dunder methods for each object. For list object, we have a dunder method __add__, which is implemented in the python list object and adds two lists.
When we use len(), python basically calls the dunder method __len__ under the hood implemented for that particular object
We can also implemented dunder methods in our custom objects.
In [50]: class Person:
...: def __init__(self, name):
...: self.name = name
...: def __repr__(self):
...: return f"{self.name}"
...: def __add__(self,x):
...: self.name = self.name + x
In [51]: p = Person("tom")
In [53]: p + "t"
In [54]: p
Out[54]: tomt