How to do Obj-C Categories in Python?

后端 未结 3 1029
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 02:49

Obj-C (which I have not used for a long time) has something called categories to extend classes. Declaring a category with new methods and compiling it into your program, all in

3条回答
  •  忘了有多久
    2021-02-06 03:31

    I came up with this implementation of a class decorator. I'm using python2.5 so I haven't actually tested it with decorator syntax (which would be nice), and I'm not sure what it does is really correct. But it looks like this:

    pycategories.py

    """
    This module implements Obj-C-style categories for classes for Python
    
    Copyright 2009 Ulrik Sverdrup 
    License: Public domain
    """
    
    def Category(toclass, clobber=False):
        """Return a class decorator that implements the decorated class'
        methods as a Category on the class @toclass
    
        if @clobber is not allowed, AttributeError will be raised when
        the decorated class already contains the same attribute.
        """
        def decorator(cls):
            skip = set(("__dict__", "__module__", "__weakref__", "__doc__"))
            for attr in cls.__dict__:
                if attr in toclass.__dict__:
                    if attr in skip:
                        continue
                    if not clobber:
                        raise AttributeError("Category cannot override %s" % attr)
                setattr(toclass, attr, cls.__dict__[attr])
            return cls
        return decorator
    

提交回复
热议问题