Skip to main content
 首页 » 编程设计

python之Python 中的继承使得所有基函数都被调用

2025年05月04日17www_RR

基本上,我想要的是这样做:

class B: 
    def fn(self): 
        print 'B' 
 
class A: 
    def fn(self): 
        print 'A' 
 
@extendInherit 
class C(A,B): 
    pass 
 
c=C() 
c.fn() 

输出为

A 
B 

我将如何实现 extendInherit 装饰器?

请您参考如下方法:

这不是装饰者的工作。你想彻底改变一个类的正常行为,所以这实际上是元类的工作。

import types 
 
class CallAll(type): 
    """ MetaClass that adds methods to call all superclass implementations """ 
    def __new__(meta, clsname, bases, attrs): 
        ## collect a list of functions defined on superclasses 
        funcs = {} 
        for base in bases: 
            for name, val in vars(base).iteritems(): 
                if type(val) is types.FunctionType: 
                    if name in funcs: 
                        funcs[name].append( val ) 
                    else: 
                        funcs[name] = [val] 
 
        ## now we have all methods, so decorate each of them 
        for name in funcs: 
            def caller(self, *args,**kwargs): 
                """ calls all baseclass implementations """ 
                for func in funcs[name]: 
                    func(self, *args,**kwargs) 
            attrs[name] = caller 
 
        return type.__new__(meta, clsname, bases, attrs) 
 
class B: 
    def fn(self): 
        print 'B' 
 
class A: 
    def fn(self): 
        print 'A' 
 
class C(A,B, object): 
    __metaclass__=CallAll 
 
c=C() 
c.fn()