我有一組對象,我正在創建一個類,我想將每個對象存儲爲自己的文本文件。我真的很想把它作爲一個Python類定義來存儲,它定義了我創建的主類的子類。所以,我做了一些探索,並在effbot.org上找到了一個Python代碼生成器。我做了一些嘗試用它,這裏就是我想出了:Python生成Python
#
# a Python code generator backend
#
# fredrik lundh, march 1998
#
# [email protected]
# http://www.pythonware.com
#
# Code taken from http://effbot.org/zone/python-code-generator.htm
import sys, string
class CodeGeneratorBackend:
def begin(self, tab="\t"):
self.code = []
self.tab = tab
self.level = 0
def end(self):
return string.join(self.code, "")
def write(self, string):
self.code.append(self.tab * self.level + string)
def indent(self):
self.level = self.level + 1
def dedent(self):
if self.level == 0:
raise SyntaxError, "internal error in code generator"
self.level = self.level - 1
class Point():
"""Defines a Point. Has x and y."""
def __init__(self, x, y):
self.x = x
self.y = y
def dump_self(self, filename):
self.c = CodeGeneratorBackend()
self.c.begin(tab=" ")
self.c.write("class {0}{1}Point()\n".format(self.x,self.y))
self.c.indent()
self.c.write('"""Defines a Point. Has x and y"""\n')
self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y))
self.c.indent()
self.c.write('self.x = {0}\n'.format(self.x))
self.c.write('self.y = {0}\n'.format(self.y))
self.c.dedent()
self.c.dedent()
f = open(filename,'w')
f.write(self.c.end())
f.close()
if __name__ == "__main__":
p = Point(3,4)
p.dump_self('demo.py')
,感覺真難看,有一個更清潔/更好/更Python的方式做到這一點?請注意,這不是我實際打算這樣做的班級,這是一個小班,我可以輕鬆地模擬出不太多的線路。另外,子類不需要在其中有生成函數,如果我再次需要,我可以從超類調用代碼生成器。
不要使用製表符縮進蟒蛇,使用空格:) – 2009-09-01 22:02:21
是的,它設置爲默認值,但我覆蓋該變量瓦特/ 4空間。 – Jonathanb 2009-09-01 22:56:40