【发布时间】:2022-01-10 06:43:31
【问题描述】:
我试图在我的类中执行某些方法之前和之后执行一个操作。
首先我考虑使用装饰器来扩展功能,如下所示:
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()
这将是输出,这是不正确的。 "after" 应该是最后要打印的内容:
before
This is do
after
This is the new implementation of do
也许还有另一种方法可以在Bar 中装饰do,所以它可以满足我的要求,但我不知道如何(如果有的话我想知道)并且每次都装饰do 不会这似乎不是一个好方法。
所以最后我想出了一个我认为不错的解决方案。定义__getattribute__so 它返回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()
这是一个好的解决方案吗?有什么缺点吗?我错过了可能在未来造成问题的东西?其他解决方法?
谢谢!!
【问题讨论】:
标签: python inheritance methods