gpt4 book ai didi

python - 在 Python2 中,如何在不明确要求最终用户包含它的情况下强制子类方法调用父方法?

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:09 25 4
gpt4 key购买 nike

我正在编写的父类在使用后需要进行一些特定的内部清理。子类有自己的清理工作要做,但父类的清理功能必须在之后运行。显然,调用 super 可以解决这个问题,但我希望这在子类方面尽可能简单。

我尝试装饰父方法。这没有用。

# The parent class whose inner-workings I don't expect the end user to understand
class ParentClass(object):
def __init__(self, *args, **kwargs):
self._personal_message = "Parent class says:"
self._important_message = "I'm important!"

# The method that NEEDS to be run in all instances of ParentClass and its subclasses
def _important_method(self):
print(self._important_message)

# The decorator I thought would work
def _pretty_decoration(func):
def func_wrapper(self):
func_self = func(self)
self._important_method()
return func_self
return func_wrapper

# The decorated function that will be overridden by the child class
@_pretty_decoration
def do_something(self):
print(self._personal_message)

# Make the decorator static
_pretty_decoration = staticmethod(_pretty_decoration)


# The blissfully naive Child class
class ChildClass(ParentClass):
def __init__(self, *args, **kwargs):
super(ChildClass, self).__init__(*args, **kwargs)
self._personal_message = "Child class says:"

# The overriding method
def do_something(self):
print(self._personal_message)
self.do_something_else()

def do_something_else(self):
print("I am blissfully naive.")


# The test drive
parent = ParentClass()
parent.do_something()
child = ChildClass()
child.do_something()

在这个例子中,我得到:

Parent class says:
I'm important!
Child class says:
I am blissfully naive.

而我希望得到:

Parent class says:
I'm important!
Child class says:
I am blissfully naive.
I'm important!

我应该怎么做才能达到预期的结果?

最佳答案

与其覆盖该方法,不如将真正的工作推迟到从 do_something 调用的回调方法。那么就没有理由覆盖 do_something,您可以直接将对 _important_method 的调用放在它的主体中。

class ParentClass(object):
def __init__(self, *args, **kwargs):
self._personal_message = "Parent class says:"
self._important_message = "I'm important!"

# The method that NEEDS to be run in all instances
# of ParentClass and its subclasses
def _important_method(self):
print(self._important_message)

# This doesn't get overriden; it's a fixed entry point to do_body
def do_something(self):
self.do_body()
self._important_method()

# This shouldn't (need to) be called directly
def do_body(self):
print(self._personal_message)


class ChildClass(ParentClass):
def do_body(self):
print(self._personal_message) # or super().do_body()
self.do_something_else()

def do_something_else(self):
print("I am blissfully naive.")

那么下面的仍然有效

child = ChildClass()
child.do_something()

关于python - 在 Python2 中,如何在不明确要求最终用户包含它的情况下强制子类方法调用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570119/

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