动态创建的类中的Python继承

Gen*_*cos 2 python monkeypatching metaclass

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

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!'
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?或者我怎么能做得更好?

Sve*_*ach 5

使用super()调用基类的方法具有一定的多重继承的情况下的优点,但缺点在大多数其他情况下(这是,在用例95%).所以根本不要super()在这里使用,而是直接调用基类方法.

我会采用另一种方式(假设我确定我真的想动态创建一个类).您可以在函数内定义整个类并返回它:

def class_factory():
    class NewFoo(foo):
        def bar(self):
            foo.bar()
            print 'another world!'
    return NewFoo
Run Code Online (Sandbox Code Playgroud)