What are `@staticmethod`, `@classmethod` and `@property`?
IntermediateConceptLanguage essentials & functions
Answer
@staticmethod: a plain function namespaced in the class, noself.@classmethod: receives the class (cls), typically for alternative constructors likeConfig.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])
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