Class / Object in 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

References

目錄

目錄
Bitnami