Class / Object in Python
- 2025.05.14
- Annotated Assignment Statements Dynamic Attribute Assignment Object-Oriented Programming Python
Definition
- attribute := class.x or obj.x
- method := callable attribute
- variable/field := non-callable attribute
class Class: cls_var_a = ... cls_var_b: type # variable annotation cls_var_c: dict[type, type] = {} # variable annotation def obj_method(self[, ...]): self.obj_var = ... ... @classmethod def cls_method(cls[, ...]): ... @staticmethod # Doesn't receive self or cls def static_method([...]): ... obj = Class([...])
Variable Annotation1PEP 526 – Syntax for Variable Annotations – Global and local variable annotations2Python Docs: Annotated assignment statements
只有var: type
時,不會建立其變數實體
僅記錄於__annotations__
Dynamic Attribute Assignment | Adding Attributes at Runtime | Monkey-Patching
a = A()
a.new_attr = ...
A.new_attr = ...
A.new_cls_method = classmethod(...)
A.new_static_method = staticmethod(...)
Last Updated on 2025/05/14 by A1go