fjptec-xm 发表于 2017-5-2 10:53:34

使用 python 模拟 ruby 的 open class

老早就写了这些代码,但一直懒得为它写篇博客,我觉得我永远也无法理解为什么会有人发明这种奇怪的东西。
不过终于还是决定写一篇吧,多一点有意思的代码也许能吸引更多人对 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(), 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 怎么样。
页: [1]
查看完整版本: 使用 python 模拟 ruby 的 open class