gpt4 book ai didi

动态创建的类中的 Python 继承

转载 作者:行者123 更新时间:2023-11-28 20:26:13 25 4
gpt4 key购买 nike

我正在尝试使用元类来实现以下功能:

class foo( object ):

def __init__( self ):
self.val = 'foo'

def bar( self ):
print 'hello world'
print self.val

f = foo()
f.bar() #prints 'hello world' followed by foo

def newbar( self ):
super( **?**, self).bar()
print 'another world!'

fooNew = type('fooNew', (foo,), {'bar':newbar})
n = fooNew()
n.bar() # should print everything in f.bar() followed by 'another world!'

我知道我可以使用猴子补丁来实现我自己的函数 newbar。但是有一个细微的差别,我希望新的 bar 函数首先运行基类 bar 函数,然后才运行任何附加功能。

我该怎么做?或者我怎样才能做得更好?

最佳答案

使用 super() 调用基类方法在某些多重继承情况下具有优势,但在大多数其他情况下(即在 95% 的用例中)具有劣势。所以这里干脆不用super(),而是直接调用基类的方法。

我会采用另一种方式(前提是我确定我真的想动态创建一个类)。您可以在函数中定义整个类并将其返回:

def class_factory():
class NewFoo(foo):
def bar(self):
foo.bar()
print 'another world!'
return NewFoo

关于动态创建的类中的 Python 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12415668/

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