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

Hàm Python có phải là object không?

Có, hàm trong Python là first-class objects (đối tượng hạng nhất).

Minh chứng

def foo():
    pass

foo.score = 20           # Gán attribute
print(type(foo))         # 
print(foo.score)         # 20
print(type(lambda x: x)) # 

Đặc điểm function object

  • Có type: function.
  • Có built-in attributes: __name__, __doc__, __module__, __annotations__, __code__, __defaults__, __closure__...
  • Có thể gán attribute tùy ý: func.custom = "data".
  • Có thể chứa nested functions.
  • Có thể truyền làm đối số, trả về, lưu trong list/dict.

Ví dụ introspection

def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

print(add.__name__)        # 'add'
print(add.__doc__)         # 'Add two numbers.'
print(add.__annotations__) # {'a': , 'b': , 'return': }
print(add.__code__.co_varnames) # ('a', 'b')

Kết luận: Function = Object + Callable. Đây là nền tảng của functional programming trong Python.