【发布时间】:2012-09-13 22:27:15
【问题描述】:
我正在尝试使用元类来实现以下功能:
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 函数,然后才运行任何附加功能。
我该怎么做?或者我怎样才能做得更好?
【问题讨论】:
-
这个问题与元类有什么关系?
-
fooNew 是使用元类类型创建的?我是元类新手,可能是错的
-
是的,
type是标准的内置元类。如果人们说“使用元类”,他们通常指的是定义 custom 元类。你在这里所做的只是使用一种相当不方便的方式来动态创建一个类。 -
谢谢斯文。创建此类的更好方法是什么?
-
我用一种方式更新了我的答案。
标签: python metaclass monkeypatching