【发布时间】:2021-08-25 16:45:26
【问题描述】:
我有一堂课如下:
class Hamburger():
topping_methods = {}
@prepare_topping("burger", "onion_ring")
def cook(self, stuff, temp):
print("cooking")
h = Hamburger()
我希望 prepare_topping 装饰器在 Hamburger.topping_methods 中添加条目,使其看起来像:
{"burger":< cook method reference >, "onion_ring": < cook method reference >}
关键是我需要在类的初始化程序运行之前 发生这种情况(真正的用例是 dict 用于在初始化程序中注册事件回调。)但是因为我要访问类变量,需要在定义类之后。
这是我对装饰器逻辑的了解:
def prepare_topping(*args):
def deco(func):
# This is when I want to add to class dict, but cannot access method arguments yet
print(eval(func.__qualname__.split(".")[0]).topping_methods) # Gets class that method belongs to in a hacky way, but the class is not yet defined
def wrapper(self, *args):
print(self.topping_methods) # Only run if the method is called, which is after __init__
return func(self, *args)
return wrapper
return deco
我意识到我永远无法访问方法 self 参数来实现这一点,因为无论该方法是否被实际调用,我都想做一些事情。有没有一种方法可以让装饰器仅在定义类之后运行?在仍然使用装饰器的同时还有其他方法可以实现这一点吗?
【问题讨论】:
-
您需要
prepare_topping来设置函数的属性,然后使用元类迭代类的属性函数并填充topping_methods(或使用超类并使用@ 987654328@). -
将其作为方法装饰器有什么意义?为什么不直接将项目添加到类主体中的类变量中?或者,如果由于某种原因你觉得有必要把它变成一个类装饰器,也许可以把它变成一个......
-
@juanpa.arrivillaga 为方便起见,有很多方法,它们订阅的事件可以经常更改。
标签: python python-3.x decorator python-decorators