Interview Prep/Python for DevOps/Language essentials & functions

What are `@staticmethod`, `@classmethod` and `@property`?

IntermediateConceptLanguage essentials & functions
Answer
  • @staticmethod: a plain function namespaced in the class, no self.
  • @classmethod: receives the class (cls), typically for alternative constructors like Config.from_yaml(path).
  • @property: a method accessed like an attribute, used for computed or validated values.
class Instance:
    def __init__(self, raw): self.raw = raw
    @property
    def name(self): return next((t["Value"] for t in self.raw.get("Tags", []) if t["Key"] == "Name"), "")
    @classmethod
    def from_id(cls, ec2, iid): return cls(ec2.describe_instances(InstanceIds=[iid])["Reservations"][0]["Instances"][0])
All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions