Junior
What methods can be used in Python to check the data type of a variable?
sobes.tech AI
Answer from AI
type(): Returns the type of an object.isinstance(): Checks if an object is an instance of a class or a subclass.
# Example with type()
var_int = 10
print(type(var_int)) # Outputs: <class 'int'>
var_str = "hello"
print(type(var_str)) # Outputs: <class 'str'>
# Example with isinstance()
var_list = [1, 2, 3]
print(isinstance(var_list, list)) # Outputs: True
print(isinstance(var_list, (list, tuple))) # Checks for multiple types
The difference between isinstance() and type() is that isinstance() considers inheritance. If an object is an instance of a subclass, isinstance() will return True when checked against the base class. type() will only return the exact type.
# Example of the difference between isinstance() and type() with inheritance
class Base:
pass
class Child(Base):
pass
child_obj = Child()
print(type(child_obj) is Child) # Outputs: True
print(type(child_obj) is Base) # Outputs: False
print(isinstance(child_obj, Child)) # Outputs: True
print(isinstance(child_obj, Base)) # Outputs: True