How to do Obj-C Categories in Python?

后端 未结 3 1066
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  萌比男神i
    2021-02-06 03:33

    Python's setattr function makes this easy.

    # categories.py
    
    class category(object):
        def __init__(self, mainModule, override = True):
            self.mainModule = mainModule
            self.override = override
    
        def __call__(self, function):
            if self.override or function.__name__ not in dir(self.mainModule):
                setattr(self.mainModule, function.__name__, function)
    

     

    # categories_test.py
    
    import this
    from categories import category
    
    @category(this)
    def all():
        print "all things are this"
    
    this.all()
    >>> all things are this
    

提交回复
热议问题