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.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner