Interview Prep/Python for DevOps/Language essentials & functions

What is a class vs an instance attribute, and what goes wrong with mutable class attributes?

IntermediateConceptLanguage essentials & functions
Answer

Class attributes are shared by all instances; instance attributes (set on self in __init__) are per object.

class Inventory:
    hosts = []              # shared by every Inventory, bug
    def __init__(self):
        self.groups = {}    # per instance, correct

Appending to self.hosts mutates the shared list, so two inventories leak hosts into each other. Constants (DEFAULT_REGION = "us-east-1") are fine as class attributes; mutable state belongs on the instance.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions