Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thuộc tính (attributes) của hàm Python

Mọi thứ trong Python là object, hàm cũng vậy. Hàm có built-in attributes và có thể gán custom attributes.

Built-in attributes

  • __name__: Tên hàm.
  • __doc__: Docstring.
  • __module__: Tên module.
  • __annotations__: Type hints dict.
  • __code__: Code object (bytecode, variables...).
  • __defaults__: Tuple default values.
  • __closure__: Tuple cells cho free variables (closure).
  • __dict__: Namespace cho custom attributes.

Gán & truy xuất custom attributes

def foo():
    pass

# Cách 1: setattr/getattr
setattr(foo, 'age', 23)
setattr(foo, 'name', 'John Doe')
print(getattr(foo, 'age'))  # 23

# Cách 2: Dot notation (tương đương)
foo.gender = 'male'
print(foo.gender)  # male

# Truy xuất tất cả
print(foo.name)   # John Doe
print(foo.age)    # 23

Đầu ra

23
male
John Doe
23

Ứng dụng

  • Metadata: version, author, deprecation info.
  • Caching: func._cache = {}.
  • Plugin system: đăng ký function với attributes.
  • Testing: mark test functions.