不过终于还是决定写一篇吧,多一点有意思的代码也许能吸引更多人对 python 的兴趣呢,呵呵。虽然我对 ruby 的这个东西有许多贬义词想说,不过想想既然有人用,也就应该有其理由吧。
且看代码:
def update( klass, bases, attrs ):
for k,v in attrs.items():
if not k.startswith('__') or not k.endswith('__'):
setattr(klass, k, v)
if bases:
klass.__bases__ = bases
return klass
class Meta(type):
def __new__(cls, klass, bases, attrs):
try:
return update( globals()[klass], bases, attrs )
except KeyError:
return type.__new__(cls, klass, bases, attrs)
# test
__metaclass__ = Meta
# test simple
class A:
def say(self):
print 'hi'
a = A()
a.say() # hi
class A:
def say(self):
print 'ho'
def new_func(self):
print 'new'
a.say() # ho
a.new_func() # new
# test inherit
#del A
#class A:
#def say(self):
#print 'hi'
#a = A()
#a.say() # hi
#class B:
#def say(self):
#print 'ho'
#class A(B):
#def say(self):
#super(A, self).say()
#a.say() # ho
update: 很遗憾,测试发现 new style class 貌似还有个 bug 。所以把后面部分注释了先,不知道 python2.5 怎么样。