gpt4 book ai didi

python - 在子类方法中向函数添加钩子(Hook)

转载 作者:行者123 更新时间:2023-12-05 01:35:19 28 4
gpt4 key购买 nike

给定以下简化代码:

from abc import ABC, abstractmethod

class Parent(ABC):
def __init__(self,*args,**kwargs):
self.parent_name = 'SuperClass'

# global hook to run before each subclass run()
def global_pre_run_hook(self):
pass

@abstractmethod
def run(self, *args, **kwargs):
raise NotImplementedError()



class Child(Parent):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.name = 'ChildClass'

def run(self):
print(f'my parent name is {self.parent_name}')
print(f'my name is {self.name}')

return 22

obj = Child()
result = obj.run()

有没有办法增加功能,让直接调用子类的run()方法时,先触发父类的hook函数?假设有一个父类和许多子类 - 我是否需要在每个 run() 定义的开头手动添加一个 call global hook()对于子类化 Parent() 的每个类?是否有 Pythonic 方法来完成此操作?

最佳答案

可能有一种方法可以使用合适的装饰器来做到这一点,但目前我认为你可能想出的最干净的解决方案是创建你自己的“装饰器”并在 Parent.__init__(),只要子类调用父类__init__(),它就会生效:

from abc import ABC, abstractmethod

def create_hook(func, hook):
def wrapper(*args, **kwargs):
hook()
return func(*args, **kwargs)
return wrapper

class Parent(ABC):
def __init__(self, *args, **kwargs):
self.parent_name = 'SuperClass'
self.run = create_hook(self.run, self.global_pre_run_hook)

# global hook to run before each subclass run()
def global_pre_run_hook(self):
print("Hooked")

@abstractmethod
def run(self, *args, **kwargs):
raise NotImplementedError()

class Child(Parent):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.name = 'ChildClass'

def run(self):
print(f'my parent name is {self.parent_name}')
print(f'my name is {self.name}')
return 22

obj = Child()
result = obj.run()
# this prints:
# Hooked
# my parent name is SuperClass
# my name is ChildClass

关于python - 在子类方法中向函数添加钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63019558/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com