我编写了 Python 类 Code,它使您能够向对象添加和删除新的代码行,打印代码并执行它。类代码显示在最后。
示例:如果 x == 1,则代码将其值更改为 x = 2,然后删除带有检查该条件的条件的整个块。
#Initialize Variables
x = 1
#Create Code
code = Code()
code + 'global x, code' #Adds a new Code instance code[0] with this line of code => internally code.subcode[0]
code + "if x == 1:" #Adds a new Code instance code[1] with this line of code => internally code.subcode[1]
code[1] + "x = 2" #Adds a new Code instance 0 under code[1] with this line of code => internally code.subcode[1].subcode[0]
code[1] + "del code[1]" #Adds a new Code instance 0 under code[1] with this line of code => internally code.subcode[1].subcode[1]
创建代码后,您可以打印它:
#Prints
print "Initial Code:"
print code
print "x = " + str(x)
输出:
Initial Code:
global x, code
if x == 1:
x = 2
del code[1]
x = 1
通过调用对象执行 cade:code()
print "Code after execution:"
code() #Executes code
print code
print "x = " + str(x)
输出 2:
Code after execution:
global x, code
x = 2
如您所见,代码将变量 x 更改为值 2 并删除了整个 if 块。这对于避免在满足条件后检查条件可能很有用。在现实生活中,这种案例场景可以由协程系统处理,但这种自我修改代码实验只是为了好玩。
class Code:
def __init__(self,line = '',indent = -1):
if indent < -1:
raise NameError('Invalid {} indent'.format(indent))
self.strindent = ''
for i in xrange(indent):
self.strindent = ' ' + self.strindent
self.strsubindent = ' ' + self.strindent
self.line = line
self.subcode = []
self.indent = indent
def __add__(self,other):
if other.__class__ is str:
other_code = Code(other,self.indent+1)
self.subcode.append(other_code)
return self
elif other.__class__ is Code:
self.subcode.append(other)
return self
def __sub__(self,other):
if other.__class__ is str:
for code in self.subcode:
if code.line == other:
self.subcode.remove(code)
return self
elif other.__class__ is Code:
self.subcode.remove(other)
def __repr__(self):
rep = self.strindent + self.line + '\n'
for code in self.subcode: rep += code.__repr__()
return rep
def __call__(self):
print 'executing code'
exec(self.__repr__())
return self.__repr__()
def __getitem__(self,key):
if key.__class__ is str:
for code in self.subcode:
if code.line is key:
return code
elif key.__class__ is int:
return self.subcode[key]
def __delitem__(self,key):
if key.__class__ is str:
for i in range(len(self.subcode)):
code = self.subcode[i]
if code.line is key:
del self.subcode[i]
elif key.__class__ is int:
del self.subcode[key]