Python type() Function
type()is a built-in function in Python used to get the type of an object.
type()is one of the most commonly used functions in Python, which helps us understand the type of an object, and is a very important tool in dynamically typed languages.
Term Explanation: type 意为"类型",用于获取对象的类型信息。
Basic Syntax and Parameters
Syntax
type(object) type(name, bases, dict)
Parameter Description
- Parameter object:
- Type: Any object
- Description: The object whose type is to be obtained.
- Parameters name, bases, dict:
- Type: String, tuple of classes, dictionary
- Description: Used to dynamically create a class.
Function Description
- Return value: Returns the type of the object (a type object).
Examples
Example 1: Get Object Type
Example
# Get the type of basic types
print(type(123)) # Output: <class 'int'>
print(type(3.14)) # Output: <class 'float'>
print(type("hello")) # Output: <class 'str'>
print(type(True)) # Output: <class 'bool'>
print(type([1, 2, 3])) # Output: <class 'list'>
print(type({"a": 1})) # Output: <class 'dict'>
print(type((1, 2))) # Output: <class 'tuple'>
print(type({1, 2})) # Output: <class 'set'>
# Type of None
print(type(None)) # Output: <class 'NoneType'>
print(type(123)) # Output: <class 'int'>
print(type(3.14)) # Output: <class 'float'>
print(type("hello")) # Output: <class 'str'>
print(type(True)) # Output: <class 'bool'>
print(type([1, 2, 3])) # Output: <class 'list'>
print(type({"a": 1})) # Output: <class 'dict'>
print(type((1, 2))) # Output: <class 'tuple'>
print(type({1, 2})) # Output: <class 'set'>
# Type of None
print(type(None)) # Output: <class 'NoneType'>
Expected output:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'list'> <class 'dict'> <class 'tuple'> <class 'set'> <class 'NoneType'>
Code analysis:
type()Returns the type object of the object.- Each type itself is also an instance of the type class.
Example 2: Compare Types
Example
# Direct comparison
value = 42
print(type(value) == int) # Output: True
print(type(value) == str) # Output: False
# Using isinstance (recommended)
print(isinstance(42, int)) # Output: True
print(isinstance("hello", str)) # Output: True
print(isinstance(42, (int, float))) # Output: True
# Check custom classes
class Dog:
pass
class Cat:
pass
dog = Dog()
print(type(dog) == Dog) # Output: True
print(type(dog) == Cat) # Output: False
print(isinstance(dog, Dog)) # Output: True
value = 42
print(type(value) == int) # Output: True
print(type(value) == str) # Output: False
# Using isinstance (recommended)
print(isinstance(42, int)) # Output: True
print(isinstance("hello", str)) # Output: True
print(isinstance(42, (int, float))) # Output: True
# Check custom classes
class Dog:
pass
class Cat:
pass
dog = Dog()
print(type(dog) == Dog) # Output: True
print(type(dog) == Cat) # Output: False
print(isinstance(dog, Dog)) # Output: True
Expected output:
True False True True True True False True
Code analysis:
- You can use
type() ==for precise type comparison. - But it is recommended to use
isinstance(), because it supports inheritance.
Example 3: Dynamically Create a Class
Example
# Create a class dynamically using type()
Person = type("Person", (), {
"name": "Unknown",
"age": 0,
"greet": lambda self: f"Hello, I am {self.name}"
})
# Use the dynamically created class
p = Person()
p.name = "Tom"
print(p.name) # Output: Tom
print(p.greet()) # Output: Hello, I am Tom
# Create a class with inheritance
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
DogClass = type("DogClass", (Animal,), {
"speak": lambda self: "Woof!"
})
dog = DogClass()
print(dog.speak()) # Output: Woof!
print(isinstance(dog, Animal)) # Output: True
Person = type("Person", (), {
"name": "Unknown",
"age": 0,
"greet": lambda self: f"Hello, I am {self.name}"
})
# Use the dynamically created class
p = Person()
p.name = "Tom"
print(p.name) # Output: Tom
print(p.greet()) # Output: Hello, I am Tom
# Create a class with inheritance
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
DogClass = type("DogClass", (Animal,), {
"speak": lambda self: "Woof!"
})
dog = DogClass()
print(dog.speak()) # Output: Woof!
print(isinstance(dog, Animal)) # Output: True
Expected output:
Dynamically creating classes is rarely used in actual programming, but understanding this is important for metaclass programming.
type()is one of the most basic and important functions in Python.
Other Extensions
Python3 Built-in Functions