python 黑魔法收集

黑魔法收集

为类的创建省略 self

from types import FunctionType
from byteplay import Code, opmap

def MetaClassFactory(function):
    class MetaClass(type):
        def __new__(meta, classname, bases, classDict):
            for attributeName, attribute in classDict.items():
                if type(attribute) == FunctionType:
                    attribute = function(attribute)

                newClassDict[attributeName] = attribute
            return  type.__new__(meta, classname, bases, classDict)
    return MetaClass

def _transmute(opcode, arg):
    if ((opcode == opmap['LOAD_GLOBAL']) and
        (arg == 'self')):
        return opmap['LOAD_FAST'], arg
    return opcode, arg

def selfless(function):
    code = Code.from_code(function.func_code)
    code.args = tuple(['self'] + list(code.args))
    code.code = [_transmute(op, arg) for op, arg in code.code]
    function.func_code = code.to_code()
    return function

Selfless = MetaClassFactory(selfless)

class Test(object):

    __metaclass__ = Selfless

    def __init__(x=None):
        self.x = x

    def getX():
        return self.x

    def setX(x):
        self.x = x

test = Test()
print(test.getX())

test.setX(7)
print(test.getX())

猜你喜欢

转载自www.cnblogs.com/Frank99/p/9146376.html