WEB开发网
开发学院软件开发Python Python 中的元类编程(3) 阅读

Python 中的元类编程(3)

 2008-09-30 12:42:40 来源:WEB开发网   
核心提示: 清单 7. classinitializer 装饰器import sysdef classinitializer(proc): # basic idea stolen from zope.interface.advice, P.J. Eby def newproc(*args, **kw)

清单 7. classinitializer 装饰器

import sys
def classinitializer(proc):
  # basic idea stolen from zope.interface.advice, P.J. Eby
  def newproc(*args, **kw):
    frame = sys._getframe(1)
    if '__module__' in frame.f_locals and not
      '__module__' in frame.f_code.co_varnames: # we are in a class
      if '__metaclass__' in frame.f_locals:
        raise SyntaxError("Don't use two class initializers orn"
         "a class initializer together with a __metaclass__ hook")
      def makecls(name, bases, dic):
        try:
          cls = type(name, bases, dic)
        except TypeError, e:
          if "can't have only classic bases" in str(e):
            cls = type(name, bases + (object,), dic)
          else: # other strange errs, e.g. __slots__ conflicts
            raise
        proc(cls, *args, **kw)
        return cls
      frame.f_locals["__metaclass__"] = makecls
    else:
      proc(*args, **kw)
newproc.__name__ = proc.__name__
newproc.__module__ = proc.__module__
newproc.__doc__ = proc.__doc__
newproc.__dict__ = proc.__dict__
return newproc

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:Python 编程

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接