1. 程式人生 > >python 黑魔法收集

python 黑魔法收集

tran meta mut self lob getx item init pri

黑魔法收集

為類的創建省略 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())

python 黑魔法收集