Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

Reducing boilerplate and cleaning up

After writing a few small tests, we often find that we have to write the same setup code for several related tests. For example, the following list subclass has three methods for statistical calculations:

from collections import defaultdict 
 
class StatsList(list): 
    def mean(self): 
        return sum(self) / len(self) 
 
    def median(self): 
        if len(self) % 2: 
            return self[int(len(self) / 2)] 
        else: 
            idx = int(len(self) / 2) 
            return (self[idx] + self[idx-1]) / 2 
 
    def mode(self): 
        freqs = defaultdict(int) 
        for item in self: 
            freqs[item] += 1 
        mode_freq = max(freqs.values()) 
        modes = [] 
        for item, value in freqs.items(): 
            if value == mode_freq: 
                modes.append(item) 
        return modes 

Clearly, we're going to want to test situations with each ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content