前提: -我有一个具有> 10个方法类的Parent和一个需要实现这10个方法的Child类。 -Child类需要为所有这些方法添加准上下文管理。我说准上下文管理是因为我确实不需要文件对象来执行操作,但是我确实需要为每种方法运行两行设置/删除操作。 -在其他子类中,父方法将不会失败,因此我不希望在父类中进行任何上下文管理。
我现在知道的示例代码可以做得更好:
class Parent(object):
def foo(self, arg1='default', argn):
print("Action that might fail: {} {}".format(arg1, argn))
class Child(Parent):
def bar(self, arg1, argn):
setup_method()
super(Child, self).bar(arg1, argn)
teardown_method()
def teardown_method()
print("This is just a new method in the Child class")
print("These two lines prevent real-world issues")
我想要的伪代码(或类似的东西):
import wrapt, inspect
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
def add_context(*args, **kwargs):
with context_man:
parent_method_of_same_name = get_parent_method(instance) # use inspect module?
calling_class = inspect.getmro(wrapped) # use inspect module?
super(calling_class, self).parent_method_of_same_name(*args, **kwargs) # use of self here?
class context_man(object):
def __enter__(self):
print("These two lines prevent real-world issues")
def __exit__(self):
print("These two lines prevent real-world issues")
return add_context(*args, **kwargs)
class Parent(object):
def foo(self, arg1='default', argn):
print("Action that might fail: {} {}".format(arg1, argn))
class Child(Parent):
@wrapper
def bar(self, args, kwargs):
pass
在处理所有> 10种方法时,这非常有利,因为我不必重复try-catch语句,也不必重复对super()的调用。但是,上述代码段显然存在很多问题:
任何帮助将不胜感激!