Python 类继承 - 如何从以前的继承继承?

时间:2021-05-30 23:54:20

标签: python-2.7

我有一堂这样的课。

 from flask.views import MethodView
 class FirstClass(MethodView):

我还有一堂这样的课。

 class SecondClass(FirstClass):

     def post(self):
         logging.info(self.request.body)

我原以为 SecondClass 会继承 MethodView 类。但它没有继承它。当有 POST 调用时,MethodView 将调用“post”def,但它不执行“post”函数。我该怎么做才能让 SecondClass 继承 MethodView 类?

我希望避免(由于代码复杂)

 class SecondClass(FirstClass, MethodView):

     def post(self):
         logging.info(self.request.body)

当我执行上述操作时,MethodView 会在有 POST 调用时启动以执行“post”函数。

2 个答案:

答案 0 :(得分:1)

它应该可以工作。 SecondClass 是 MethodView 的间接儿子。 SecondClass 拥有 MethodView 拥有的所有公共方法和成员,因为所有这些都是通过 FirstClass 继承的。

答案 1 :(得分:1)

SecondClass 的 post 方法覆盖了 MethodView 的 post 方法。

要在 SecondClass 的 post 方法中评估 MethodView 的 post 方法,请使用 super() 函数

class SecondClass(FirstClass, MethodView):

     def post(self):
         logging.info(self.request.body)
         super(SecondClass, self).post()

More here on the super function

相关问题