python 黑魔法收集
Posted 拂髯客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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())
以上是关于python 黑魔法收集的主要内容,如果未能解决你的问题,请参考以下文章