Python实现IOC
在一次python项目中,想要实现将一些类进行集中管理,进行解耦。于是想到了Spring的IOC功能,将bean集中管理。 经过查询找到了Python社区中有IOC的第三方库
安装IOC第三方库
pip install ioc
实现
创建配置yml配置文件 services.yml
services:
A1:
class: apps.A.A
B1:
class: apps.B.B
在apps里创建A.py和B.py
class A:
def execution(self):
return "进行A类的execution方法"
class B:
def execution(self):
print("进行B类的execution方法")
获取容器
import sys
sys.path.append("../")
import ioc
def test():
container = ioc.build(['services.yml'])
print(container.get("A1").execution())
container.get("B1").execution()
if __name__ == '__main__':
test()
"""
进行A类的execution方法
进行B类的execution方法
"""
这样就可以通过id获取容器中所初始化的对象