Logo

Personal Ops Runbook

Personal runbook covering infrastructure operations for Cloud, Kubernetes, OpenStack, and Ceph environments. Includes deployment and teardown procedures, node management, cluster monitoring setup, and incident response workflows compiled from day-to-day operational work. Intended strictly for personal reference — configurations and scripts are environment-specific and not guaranteed to work as-is elsewhere.

[Python] Lesson 49 – Functions to variables


Trong Python, một hàm có thể được gán cho một biến, và biến đó sẽ trở thành một đối tượng hàm, được sử dụng tương tự như hàm gốc. Kỹ thuật này được gọi là “functions to variables” (hàm thành biến).

Cú pháp khai báo:

variable_name = function_name

Trong đó:

  • variable_name: tên biến muốn gán hàm
  • function_name: tên hàm muốn gán cho biến

Ví dụ:

  1. Gán hàm sum cho biến my_func và sử dụng biến my_func để tính tổng của hai số.
def sum(a, b):
    return a + b

my_func = sum
print(my_func(2, 3))  # kết quả là 5

Gán hàm sorted cho biến my_func và sử dụng biến my_func để sắp xếp một danh sách các số.

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_func = sorted
print(my_func(my_list))  # kết quả là [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Gán hàm len cho biến my_func và sử dụng biến my_func để tính độ dài của một chuỗi.

my_str = "Hello, world!"
my_func = len
print(my_func(my_str))  # kết quả là 13

Kỹ thuật “functions to variables” rất hữu ích trong Python, đặc biệt là khi ta muốn truyền một hàm như một đối số vào một hàm khác. Bằng cách này, ta có thể truyền các hàm khác nhau vào cùng một hàm, giúp việc lập trình trở nên linh hoạt và tiện lợi hơn.