python实现--文件Demo1

# -*- coding: utf-8 -*-
"""
Created on Sat Feb  3 16:21:52 2018

@author: Administrator

接收用户的输入并存储为新的文件
"""

filename=input('请输入存储的文件名,例如:a林.txt :')
list_content=[]
content=input('请输入文件内容(单独输入"w"保存退出):')

while content!='w':
    list_content.insert(0,content)
    content=input()
    
f_w=open(filename,'a')
f_w.writelines(list_content)
f_w.close()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,我很乐意为您介绍Python反射机制实现插件化的demo。下面是Python反射机制实现插件化的demo的基本思路: 1.定义一个基础类或接口,这个基础类或接口是插件实现的约定。 2.定义插件路径,把插件放在指定的路径下,并使用`os`模块自动发现插件。 3.使用反射加载插件,在插件列表中寻找并动态导入插件,使用反射实例化插件并调用其方法完成插件操作。 下面是示例代码,您可以参考: ```python # demo_plugin.py: class DemoPlugin: def execute(self): print("Demo plugin executed") # demo.py: import os import importlib.util class PluginManager: def __init__(self, plugin_path): self.plugins = [] self.plugin_path = plugin_path def discover_plugins(self): for filename in os.listdir(self.plugin_path): if filename.endswith(".py"): plugin_filepath = os.path.join(self.plugin_path, filename) spec = importlib.util.spec_from_file_location(filename[:-3], plugin_filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for name in dir(module): obj = getattr(module, name) try: if issubclass(obj, Plugin) and obj is not Plugin: self.plugins.append(obj()) except TypeError: pass def run_all_plugins(self): for plugin in self.plugins: plugin.execute() if __name__ == "__main__": plugin_manager = PluginManager(".") plugin_manager.discover_plugins() plugin_manager.run_all_plugins() ``` 假设我们有一个名为`demo_plugin.py`的插件,其中定义了名为`DemoPlugin`的类。执行`demo_plugin.py`后会创建一个`PluginManager`对象,并指定插件路径为当前路径(".")。使用`discover_plugins()`方法自动找到所有以`.py`结尾的文件,并尝试使用反射导入它们。如果该模块中包含正确的插件类,则将其实例化并添加到插件列表中。然后,使用`run_all_plugins()`方法依次执行所有插件中的`execute()`方法。在这种情况下,`DemoPlugin`中的`execute()`方法将在控制台中打印一条简单的消息。 希望这个demo可以帮助到您,有任何问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值