老早就写了这些代码,但一直懒得为它写篇博客,我觉得我永远也无法理解为什么会有人发明这种奇怪的东西。 不过终于还是决定写一篇吧,多一点有意思的代码也许能吸引更多人对 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
0 评论:
发表评论