簡體   English   中英

動態創建的類中的Python繼承

[英]Python inheritance in dynamically created classes

我正在嘗試使用元類來實現以下功能:

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

您可以更改newbar的定義以返回函數:

def newbar_factory(cls):
    def newbar(self):
        super(cls, self).bar()
        # Alternately, as Sven points out you could do
        # cls.bar(self)
        print "another world!"

    return newbar

# Use
fooNew = type('fooNew', (foo,), {'bar':newbar_factory(foo)})

可能有更好的方法來完成你想要做的事情 - 但這應該可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM