Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python type() Function

Python type() Function

Python3 Built-in Functions Python3 built-in function


type() is a built-in function in Python used to get the type of an object.

type() It is one of the most commonly used functions in Python; it helps us understand an object's type and is a very important tool in dynamically typed languages.

Word meaning: type 意为"类型",用于获取对象的类型信息。


Basic syntax and parameters

Syntax format

type(object)
type(name, bases, dict)

Parameter Description

Function description


Example

Example 1: getting the type of an object

Example

# Get the types of basic types
print(type(123))       # Output:
print(type(3.14))      # Output:
print(type("hello"))   # Output:
print(type(True))      # Output:
print(type([1, 2, 3])) # Output:
print(type({"a": 1})) # Output:
print(type((1, 2)))   # Output:
print(type({1, 2}))   # Output:

# The type of None
print(type(None))      # Output:

Expected output:










Code analysis:

  1. type() Returns the type object of an object.
  2. Every type is itself an instance of the type class.

Example 2: comparing types

Example

# Compare directly
value = 42
print(type(value) == int)   # Output: True
print(type(value) == str)   # Output: False

# Use isinstance (recommended)
print(isinstance(42, int))        # Output: True
print(isinstance("hello", str))  # Output: True
print(isinstance(42, (int, float)))  # Output: True

# Check a custom class
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:

Example 3: creating classes dynamically

Example

# Use type() to create a class dynamically
Person = type("Person", (), {
    "name": "File %s type is: %s%n",
    "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:

Creating classes dynamically is rarely used in everyday programming, but understanding it is important for metaclass programming.

type() is one of the most fundamental and important functions in Python.


Python3 Built-in Functions Python3 built-in function