我最近在和一些人谈论我正在编写的程序时听到了“hook”这个词。我不确定这个术语到底意味着什么,尽管我从对话中推断钩子是一种函数类型。我寻找一个定义,但无法找到一个好的答案。有没有人能告诉我这个术语的一般含义,或者举个小例子来说明这个定义?
当前回答
在Drupal内容管理系统中,“hook”有一个相对特定的含义。当内部事件发生时(例如内容创建或用户登录),模块可以通过实现一个特殊的“钩子”函数来响应该事件。这是通过命名约定完成的——例如,用户登录事件的[your-plugin-name]_user_login()。
由于这种惯例,底层事件被称为“钩子”,并在Drupal的API文档中以“hook_user_login”和“hook_user_authenticate()”这样的名称出现。
其他回答
通常挂钩指的是Win32消息挂钩或Linux/OSX的等等物,但更一般的挂钩只是通知另一个对象/窗口/程序等,当指定的操作发生时,你想被通知。例如:让系统上的所有窗口在即将关闭时通知您。
作为一般规则,钩子有点危险,因为在不了解它如何影响系统的情况下这样做可能会导致不稳定或至少是意想不到的行为。在某些情况下,它也非常有用。例如:FRAPS使用它来确定应该在哪个窗口显示FPS计数器。
Hook表示在代码中分派某个类型的事件的位置,如果该事件在此之前已使用适当的函数进行回调,那么它将由这个已注册的函数处理,否则什么都不会发生。
答案很多,但没有例子,所以添加一个虚拟的:下面的complated_func提供了两个钩子来修改它的行为
from typing import List, Callable
def complicated_func(
lst: List[int], hook_modify_element: Callable[[int], int], hook_if_negative=None
) -> int:
res = sum(hook_modify_element(x) for x in lst)
if res < 0 and hook_if_negative is not None:
print("Returning negative hook")
return hook_if_negative
return res
def my_hook_func(x: int) -> int:
return x * 2
if __name__ == "__main__":
res = complicated_func(
lst=[1, 2, -10, 4],
hook_modify_element=my_hook_func,
hook_if_negative=0,
)
print(res)
简单的说:
钩子是在现有代码之前、之后或代替现有代码执行自定义代码(函数)的一种方法。例如,为了在继续正常登录过程之前执行验证码函数,可以编写一个函数“hook”到登录过程中。
A chain of hooks is a set of functions in which each function calls the next. What is significant about a chain of hooks is that a programmer can add another function to the chain at run time. One way to do this is to look for a known location where the address of the first function in a chain is kept. You then save the value of that function pointer and overwrite the value at the initial address with the address of the function you wish to insert into the hook chain. The function then gets called, does its business and calls the next function in the chain (unless you decide otherwise). Naturally, there are a number of other ways to create a chain of hooks, from writing directly to memory to using the metaprogramming facilities of languages like Ruby or Python.
钩子链的一个例子是MS Windows应用程序处理消息的方式。处理链中的每个函数要么处理消息,要么将其发送给链中的下一个函数。