gpt4 book ai didi

python - 在 Python 中实现装饰器模式

转载 作者:IT老高 更新时间:2023-10-28 22:21:18 24 4
gpt4 key购买 nike

我想实现 decorator pattern在 Python 中,我想知道是否有一种方法可以编写一个只实现它想要修改的函数的装饰器,而无需为所有刚刚转发给装饰对象的函数编写样板。像这样:

class foo(object):
def f1(self):
print "original f1"
def f2(self):
print "original f2"

class foo_decorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def f1(self):
print "decorated f1"
self._decoratee.f1()
def f2(self): # I would like to leave that part out
self._decoratee.f2()

我希望对 foo_decorator.f2 的调用自动转发到 decoratee.f2。有没有办法编写一个通用方法,将所有未实现的函数调用转发到 decoratee

最佳答案

你可以使用 __getattr__:

class foo(object):
def f1(self):
print "original f1"
def f2(self):
print "original f2"

class foo_decorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def f1(self):
print "decorated f1"
self._decoratee.f1()
def __getattr__(self, name):
return getattr(self._decoratee, name)

u = foo()
v = foo_decorator(u)
v.f1()
v.f2()

关于python - 在 Python 中实现装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118929/

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