Fundamentals 8 min read

Common Built-in Classes in Python: Numbers, Sequences, Mappings, Sets, Files, Others, Exceptions, Special Methods, Iterators, and Reflection

This article introduces Python's most frequently used built-in classes—including numeric, sequence, mapping, set, file, miscellaneous, exception, special method, iterator, and reflection types—explaining their purposes and providing clear code examples that demonstrate how to create, inspect, and manipulate each class.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Common Built-in Classes in Python: Numbers, Sequences, Mappings, Sets, Files, Others, Exceptions, Special Methods, Iterators, and Reflection

1. Numeric Types

Python provides int , float , and complex classes to represent integers, floating‑point numbers, and complex numbers respectively.

num = 10
print(num)               # 10
print(type(num))          #
num = 3.14
print(num)               # 3.14
print(type(num))          #
num = 3 + 4j
print(num)               # (3+4j)
print(type(num))          #

2. Sequence Types

Sequences include str , list , tuple , and range , each serving different use‑cases such as text handling, mutable collections, immutable ordered collections, and generated integer ranges.

s = "Hello, world!"
print(s)                  # Hello, world!
print(type(s))           #
lst = [1, 2, 3, 4]
print(lst)                # [1, 2, 3, 4]
print(type(lst))          #
t = (1, 2, 3, 4)
print(t)                  # (1, 2, 3, 4)
print(type(t))            #
r = range(5)
print(r)                  # range(0, 5)
print(type(r))           #
print(list(r))            # [0, 1, 2, 3, 4]

3. Mapping Type

The dict class implements hash‑based key‑value mappings.

d = {'name': 'Alice', 'age': 25}
print(d)                  # {'name': 'Alice', 'age': 25}
print(type(d))            #

4. Set Types

Python offers mutable set and immutable frozenset for unordered collections of unique elements.

s = {1, 2, 3, 4}
print(s)                  # {1, 2, 3, 4}
print(type(s))            #
fs = frozenset({1, 2, 3, 4})
print(fs)                 # frozenset({1, 2, 3, 4})
print(type(fs))           #

5. File Type

File objects are created with open and support reading and writing.

with open('example.txt', 'w') as f:
    f.write('Hello, world!\n')

with open('example.txt', 'r') as f:
    content = f.read()
    print(content)        # Hello, world!
print(type(f))           #

6. Other Built‑in Types

Includes bool , bytes , bytearray , and memoryview , covering boolean values, immutable and mutable byte sequences, and buffer‑protocol views.

flag = True
print(flag)              # True
print(type(flag))        #
b = b'Hello, world!'
print(b)                 # b'Hello, world!'
print(type(b))           #
ba = bytearray(b'Hello, world!')
print(ba)                # bytearray(b'Hello, world!')
print(type(ba))          #
mv = memoryview(b)
print(mv)                #
print(type(mv))          #

7. Exception Types

Base classes for error handling include BaseException , Exception , ArithmeticError , LookupError , TypeError , and ValueError .

try:
    raise Exception("An error occurred")
except BaseException as e:
    print(e)            # An error occurred

try:
    raise ValueError("Invalid value")
except Exception as e:
    print(e)            # Invalid value

try:
    1 / 0
except ArithmeticError as e:
    print(e)            # division by zero

try:
    d = {'key': 'value'}
    d['nonexistent_key']
except LookupError as e:
    print(e)            # key 'nonexistent_key' not found

try:
    1 + '2'
except TypeError as e:
    print(e)            # unsupported operand type(s) for +: 'int' and 'str'

try:
    int('abc')
except ValueError as e:
    print(e)            # invalid literal for int() with base 10: 'abc'

8. Special Method Type

The object class is the ultimate base for all classes.

obj = object()
print(obj)               #
print(type(obj))         #

9. Iterator Types

iter creates an iterator from an iterable, and next retrieves successive elements.

lst = [1, 2, 3]
it = iter(lst)
print(next(it))          # 1
print(next(it))          # 2
print(next(it))          # 3

10. Reflection Types

Functions like type , dir , getattr , setattr , and hasattr allow inspection and dynamic manipulation of objects.

obj = 10
print(type(obj))         #
print(dir(obj))          # ['__abs__', '__add__', ...]

class Person:
    name = "Alice"

p = Person()
print(getattr(p, "name"))          # Alice
print(getattr(p, "age", 25))      # 25

setattr(p, "name", "Bob")
print(p.name)                       # Bob

print(hasattr(p, "name"))         # True
print(hasattr(p, "age"))          # False

11. Metaclass Type

The type function can be used as a metaclass to create new classes dynamically.

MyType = type('MyType', (), {'attr': 'value'})
obj = MyType()
print(obj.attr)          # value

Through the above sections, we have detailed the commonly used built‑in classes in Python, covering numeric, sequence, mapping, set, file, miscellaneous, exception, special method, iterator, and reflection categories, which help developers write more efficient Python code and solve a variety of practical problems.

reflectionbuilt-in classesexceptions
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.