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))          # <class 'int'>

num = 3.14
print(num)               # 3.14
print(type(num))          # <class 'float'>

num = 3 + 4j
print(num)               # (3+4j)
print(type(num))          # <class 'complex'>

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))           # <class 'str'>

lst = [1, 2, 3, 4]
print(lst)                # [1, 2, 3, 4]
print(type(lst))          # <class 'list'>

t = (1, 2, 3, 4)
print(t)                  # (1, 2, 3, 4)
print(type(t))            # <class 'tuple'>

r = range(5)
print(r)                  # range(0, 5)
print(type(r))           # <class 'range'>
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))            # <class 'dict'>

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))            # <class 'set'>

fs = frozenset({1, 2, 3, 4})
print(fs)                 # frozenset({1, 2, 3, 4})
print(type(fs))           # <class 'frozenset'>

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!
')

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

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))        # <class 'bool'>

b = b'Hello, world!'
print(b)                 # b'Hello, world!'
print(type(b))           # <class 'bytes'>

ba = bytearray(b'Hello, world!')
print(ba)                # bytearray(b'Hello, world!')
print(type(ba))          # <class 'bytearray'>

mv = memoryview(b)
print(mv)                # <memory at 0x...>
print(type(mv))          # <class 'memoryview'>

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)               # <object object at 0x...>
print(type(obj))         # <class 'object'>

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))         # <class 'int'>
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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.