liveBook · Manning

Atomic type

As explained in Python Workout, Second Edition

A type is a classification of Python objects that determines their values, behavior, and supported operations.

A type classifies Python objects, distinguishing their values and determining which operations and methods apply. Python keeps integers, strings, floats, sequences, and domain-specific classes distinct. section 2.18 section 10.1

Use types to reason about:

  • Whether values support an operation such as +; numbers add, strings concatenate, and lists or tuples combine. section 4.6
  • What indexing and slicing return: an indexed element may have any type, while a sequence slice preserves its sequence type. section 4.3
  • Whether a generic structure should become a domain-specific class with behavior attached as methods. section 10.1

One operation, several types

A type-flexible mysum function can combine numbers, strings, lists, or tuples when all arguments share a compatible + operation; it should reject sets and dictionaries. section 4.6

class ScoreList():
    def __init__(self, scores):
        self.scores = scores

    def average(self):
        return sum(self.scores) / len(self.scores)

scores = ScoreList([85, 95, 98, 87, 80, 92])
print(f'The final score is {scores.average()}.')

Compare a generic list-based calculation with a ScoreList class that packages the data and its average method. section 10.1

How Python Workout, Second Edition covers it

How deep it goes
Works through strong typing, operator compatibility, sequence results, and the organizational distinction between classes and generic structures.
Examples
Uses numeric conversions, a polymorphic mysum exercise, sequence slicing, and a ScoreList average implementation.
What you can do after
Evaluate/understand which operations values support and when a domain concept merits a dedicated class.
How it connects
Connects types with objects, classes, methods, sequences, indexing, slicing, and dynamic languages.

Also explained in

Compare how 17 books explain atomic type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.