gpt4 book ai didi

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

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

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

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()

关于python - Python 中的继承使得所有基函数都被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1859848/

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