Mam grupę obiektów, dla których tworzę klasę, dla której chcę przechowywać każdy obiekt jako własny plik tekstowy. Naprawdę chciałbym zapisać go jako definicję klasy Python, która podklasuje główną klasę, którą tworzę. Zrobiłem trochę pokręcenia i znalazłem generator kodu Pythona na stronie effbot.org. Zrobiłem kilka eksperymentów z nim i oto co wymyśliłem:Python generujący 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')
że czuje się naprawdę brzydki, jest tam czystsze/lepiej/bardziej pythonic sposób to zrobić? Proszę zauważyć, że nie jest to klasa, w której zamierzam to zrobić, jest to mała klasa, którą mogę z łatwością wykpić w niezbyt wielu liniach. Ponadto, podklasy nie muszą mieć w nich funkcji generującej, jeśli potrzebuję tego ponownie, mogę po prostu wywołać generator kodu z nadklasy.
Nie używaj tabulatorów do wcięcia pytona, używaj spacji :) –
tak, ustawia to jako domyślną, ale nadpisuję tę zmienną w/4 spacji. – Jonathanb