a=10
b=10.5
c=‘Python’
print(a+c)
print(a+b)
If you type (responses included):
type(a)
<class 'int'>
type(c)
<class 'str'>
type(b)
<class 'float'>
Python ‘knows’ and ‘identifies’ the differences.
But on to ‘how’ Python ‘knows’, perhaps if Python detects a period ‘.’ after an integer, then it determines that it is a float. If there are no periods in a number, then it must be an integer. If it detects opening and closing quotes, then it determines that it must be a string, even if: ‘3454’, for example.
As indicated in the first answer, the type function is used to check the types of the two objects to add, and determine if the addition is allowed/defined. The check is performed in the __add__ method.
From the official documentation (3. Data model — Python 3.12.1 documentation) of the __add__ method:
For instance, to evaluate the expression
x + y, where x is an instance of a class that has an__add__()method,type(x).__add__(x, y)is called. (…) If [the__add__()] method does not support the operation with the supplied arguments, it should returnNotImplemented.
There is nothing to “identify”. Every object stores information about its own type, and each type can have its own code for operators, and the operation works or does not work according to whether there is code provided fro it.
Paul described part of how Python decided what type of object to make from code. When it does so, it stores the type/class itself as the object’s __class__ attribute.
>>> n = 1
>>> n.__class__
<class 'int'>
>>> n.__class__ is int
True
>>> c = 'a'
>>> c.__class__
<class 'str'>