मेरे पास ऑब्जेक्ट्स का एक समूह है जिसे मैं कक्षा बना रहा हूं, मैं प्रत्येक ऑब्जेक्ट को अपनी टेक्स्ट फ़ाइल के रूप में स्टोर करना चाहता हूं। मैं वास्तव में इसे एक पायथन कक्षा परिभाषा के रूप में संग्रहीत करना चाहता हूं जो मुख्य वर्ग को बना रहा है जो मैं बना रहा हूं। तो, मैंने कुछ पोकिंग किया और effbot.org पर पाइथन कोड जेनरेटर पाया। मैं कुछ इसे के साथ प्रयोग किया है और यहाँ क्या मैं के साथ आया है:पायथन उत्पन्न पाइथन
#
# 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')
यह वास्तव में बदसूरत लगता है, वहाँ एक क्लीनर/बेहतर/अधिक pythonic यह करने के लिए तरीका है? कृपया ध्यान दें, यह वह कक्षा नहीं है जिसका मैं वास्तव में ऐसा करने का इरादा रखता हूं, यह एक छोटी सी कक्षा है जिसे मैं आसानी से कई लाइनों में नकल नहीं कर सकता हूं। साथ ही, उप-वर्गों में उन्हें उत्पन्न करने की आवश्यकता नहीं है, अगर मुझे दोबारा ज़रूरत है, तो मैं सिर्फ सुपर जेनरेटर से कोड जनरेटर को कॉल कर सकता हूं।
इंडेंट पायथन में टैब का उपयोग न करें, रिक्त स्थान का उपयोग करें :) –
हाँ, यह डिफ़ॉल्ट के रूप में सेट करता है, लेकिन मैं उस चर w/4 रिक्त स्थान को ओवरराइट करता हूं। – Jonathanb