Confirmar con isinstance()
En este paso, exploraremos la función isinstance() en Python, que proporciona otra forma de verificar el tipo de dato de una variable. La función isinstance() comprueba si un objeto es una instancia de una clase o tipo especificado. Esto es especialmente útil para escenarios de comprobación de tipos más complejos.
Continuemos modificando el archivo integers.py. Abre integers.py en el editor VS Code y agrega las siguientes líneas de código:
## Assigning integer values to variables
x = 10
y = -5
z = 0
## Printing the values of the variables
print("The value of x is:", x)
print("The value of y is:", y)
print("The value of z is:", z)
## Using the type() function to identify the data type
print("The type of x is:", type(x))
print("The type of y is:", type(y))
print("The type of z is:", type(z))
## Using isinstance() to confirm the data type
print("Is x an integer?", isinstance(x, int))
print("Is y an integer?", isinstance(y, int))
print("Is z an integer?", isinstance(z, int))
En este código, hemos agregado tres nuevas declaraciones print() que utilizan la función isinstance() para comprobar si las variables x, y y z son instancias de la clase int. La función isinstance() devuelve True si el objeto es una instancia de la clase especificada y False en caso contrario.
Ahora, ejecuta el script nuevamente utilizando el siguiente comando en la terminal:
python integers.py
Deberías ver la siguiente salida:
The value of x is: 10
The value of y is: -5
The value of z is: 0
The type of x is: <class 'int'>
The type of y is: <class 'int'>
The type of z is: <class 'int'>
Is x an integer? True
Is y an integer? True
Is z an integer? True
La función isinstance() confirma que x, y y z son en efecto enteros. Este método suele ser preferido sobre type() por su flexibilidad, especialmente cuando se trata de herencia y polimorfismo.