Python-在调用继承的方法时创建其他语句

Python-在调用继承的方法时创建其他语句,python,Python,假设我有这个: class Foo: ... def func(): return 1+2 class Bar(Foo): ... def another_func(): # additional stuff I want to do when my parent's func() is called 我不想重写func,但我确实想在调用它时添加一些附加语句。另外,我不想更改原始的Foo.func 有可能吗?如果没有,有什么解决

假设我有这个:

class Foo:
    ...
    def func():
        return 1+2

class Bar(Foo):
    ...
    def another_func():
        # additional stuff I want to do when my parent's func() is called
我不想重写
func
,但我确实想在调用它时添加一些附加语句。另外,我不想更改原始的
Foo.func


有可能吗?如果没有,有什么解决办法吗?

没有办法,规范的解决方案是覆盖函数并像这样包装原始函数:

class Bar(Foo):
    ...
    def func():
        # additional stuff I want to do when my parent's func() is called
        res = super(Bar, self).func()  # super().func() on Py3
         # additional stuff I want to do after my parent's func() is called
        return res

您需要重写
func
函数,并从其中调用父函数的
func
。Python为此目的:

super(类型[,对象或类型])

返回一个代理对象,该对象将方法调用委托给类型为的父类或同级类。 这对于访问类中已重写的继承方法非常有用。 搜索顺序与getattr()使用的相同,只是跳过了类型本身

例如:

class Foo(object):    
    def func(self):
        print "In parent"

class Bar(Foo):
    def func(self):
        super(Bar, self).func()
        print 'In child'   # Your additonal stuff
当您运行
栏的
功能时,如下所示:

b = Bar()
b.func()
将打印:

In parent   #  <-- from Foo.func()
In child    #  <-- from Bar.func()

在《家长》中,我不太清楚你的确切意思。是要调用func然后执行其他操作,还是要修改func本身?还是要传递其他参数?或者…?您能否更具体地说明为什么不想覆盖
func
?通常这正是您要做的,给子类一个
func
,它调用父类
func
,然后做其他事情。