The type() function retrieves the type of an object or dynamically creates a new class. It’s useful for debugging, type checking, and metaprogramming.
Example
x = 10
print(type(x))
Output:
<class 'int'>
Returns the type of x as int.
Syntax
1. Get Type of an Object
type(object)
- object → The variable whose type is needed.
- Returns → The class type of the object.
2. Create a New Class Dynamically
type(class_name, bases, attributes)
- class_name → Name of the new class.
- bases → Tuple of parent classes (inheritance).
- attributes → Dictionary of attributes and methods.
- Returns → A new class.
1. Checking the Type of Different Objects
print(type(5)) # Output:
print(type(3.14)) # Output:
print(type("Hello")) # Output:
print(type([1, 2, 3])) # Output:
Works on all Python objects.
2. Using type() for Conditional Checks
x = "Python"
if type(x) == str:
print("x is a string")
Checks if x is a string.
3. Using isinstance() Instead of type() (Better for Inheritance)
class Animal: pass
class Dog(Animal): pass
d = Dog()
print(type(d) == Dog) # Output: True
print(type(d) == Animal) # Output: False
print(isinstance(d, Animal)) # Output: True
Use isinstance() instead of type() when dealing with inheritance.
4. Creating a New Class Using type()
Person = type("Person", (), {"greet": lambda self: "Hello!"})
p = Person()
print(p.greet())
# Output: Hello!
Dynamically creates a class named Person with a method greet().
Key Notes
- ✔ Retrieves an object’s type.
- ✔ Supports all data types (
int,float,list,dict, etc.). - ✔ Can dynamically create new classes.
- ✔ Use
isinstance()for checking inheritance.
By using type(), you can identify object types, create classes dynamically, and perform advanced metaprogramming. 🚀