欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python代码导出_代码生成 – Python生成Python

发布时间:2024/7/23 python 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python代码导出_代码生成 – Python生成Python 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我有一组对象,我正在创建一个类,我想要将每个对象存储为自己的文本文件.我真的希望将其存储为一个

Python类定义,它会分类我正在创建的主类.所以,我做了一些戳,并在effbot.org上找到了一个Python代码生成器.我做了一些实验,这里是我想出来的:

#

# a Python code generator backend

#

# fredrik lundh, march 1998

#

# fredrik@pythonware.com

# 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方式来做到这一点?请注意,这不是我真的打算这样做的课程,这是一个小班,我可以很容易地模拟不要太多的行.此外,子类不需要在其中具有生成函数,如果我再次需要,我可以从超类调用代码生成器.

总结

以上是生活随笔为你收集整理的python代码导出_代码生成 – Python生成Python的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。