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
















