gpt4 book ai didi

python - 在方法执行之前和之后做一些事情

转载 作者:行者123 更新时间:2023-12-05 03:34:05 25 4
gpt4 key购买 nike

我试图在我的类中执行某些方法之前和之后执行一个操作。
首先我想到了使用装饰器来扩展功能,就像这样:

def decorator(f):
def wrap(*args, **kwargs):
print("before")
f(*args, **kwargs)
print("after")

return wrap


class Foo(object):

@decorator
def do(self):
print("This is do")


a = Foo()
a.do()

这输出了我想要的:

before
This is do
after

但后来我意识到,如果我想从 Foo 继承来扩展 do 那是行不通的,至少我这样做的方式是这样:

class Bar(Foo):

def do(self):
super(Bar, self).do()
print("This is the new implementation of do")


b = Bar()
b.do()

这将是输出,但不行。 “之后”应该是最后要打印的东西:

before
This is do
after
This is the new implementation of do

也许还有另一种方法可以装饰 Bar 中的 do 所以它可以做我想要的但我不知道如何(如果有我想知道它) 和 tbh 每次都装饰 do 似乎不是一个好方法。

所以最后我想出了一个我认为不错的解决方案。定义 __getattribute__ 以便它返回 do 的包装器:

class Foo(object):
def __getattribute__(self, name):
attribute = super(Foo, self).__getattribute__(name)
if name == "do":
def wrap(*args, **kwargs):
print("before")
attribute(*args, **kwargs)
print("after")
return wrap

else:
return attribute

def do(self):
print("This is do")


class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()

def do(self):
super(Bar, self).do()
print("This is the new implementation of do")


a = Bar()
a.do()

这是一个好的解决方案吗?有什么缺点吗?我遗漏了一些可能在将来造成问题的东西吗?其他解决方法?

谢谢!!

最佳答案

您可以使用 __wrapped__ 访问 python3 中的包装函数,因为它是一个自定义装饰器,您需要使用 functools.wraps 装饰器稍作修改。

from functools import wraps

def decorator(f):
@wraps(f)
def wrap(*args, **kwargs):
print("before")
f(*args, **kwargs)
print("after")

return wrap

将装饰器重新应用到新的 do() 并将其从旧的中剥离

class Bar(Foo):
@decorator
def do(self):
super(Bar, self).do.__wrapped__(super)
print("This is the new implementation of do")

你得到:

before
This is do
This is the new implementation of do
after

关于python - 在方法执行之前和之后做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70222079/

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