在Python中生成代码可以通过多种方式实现,以下是一些常见的方法:
使用`range()`函数生成整数序列
for i in range(5):print(i)
列表推导式生成列表
squares = [x2 for x in range(10)]print(squares)
使用`random`模块生成随机整数数组
import randomlength = 10minimum = 1maximum = 100random_array = []for _ in range(length):random_num = random.randint(minimum, maximum)random_array.append(random_num)print(random_array)
动态生成代码并导出为`.py`文件
def gen(tmpl, out):if not os.path.exists(out):os.makedirs(out)files = os.listdir(tmpl)for f in files:if os.path.isdir(tmpl + '/' + f):gen(tmpl + '/' + f, out + '/' + f)else:gen_one_file(tmpl + '/' + f, get_out_filename(f, out), config_dict)def gen_one_file(tmpl, target, config_dict):filePath = targetwith open(filePath, 'w') as file:file.write(Template(open(tmpl).read()).substitute(config_dict))
使用带名称的格式化参数特性
def make_collection_class(entity_name, entity_comment):template = """using System.Collections;namespace SomeNameSpace.Model {/// %(entity_comment)s集合public class %(entity_name)sCollection : CollectionBase {public %(entity_name)sCollection() { }public void Add(%(entity_name)s obj) { base.InnerList.Add(obj); }public void Remove(%(entity_name)s obj) { base.InnerList.Remove(obj); }public %(entity_name)s this[int i] { get { return (%(entity_name)s) base.InnerList[i]; } set { base.InnerList[i] = value; } }}}"""return Template(template).substitute(entity_name=entity_name, entity_comment=entity_comment)
编写一个简单的Python程序
import sysdef main():print("Hello, world!")if __name__ == "__main__":main()

