• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
python面向对象之依赖注入
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 组合
# a = a()
# b = b(a)
# c = c(b)
# d = d(c)
#依赖注入

class Mapper:
__mapper_relation = {}

@staticmethod
def register(cls,value):
Mapper.__mapper_relation[cls]=value

@staticmethod
def exist(cls):
if cls in Mapper.__mapper_relation:
return True
return False

@staticmethod
def value(cls):
return Mapper.__mapper_relation[cls]



class MyType(type):
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls,*args,**kwargs)
arg_list = list(args)
if Mapper.exist(cls):
value = Mapper.value(cls)
arg_list.append(value)
obj.__init__(*arg_list,**kwargs)
return obj

class Foo(metaclass=MyType):
def __init__(self,name):
self.name=name

def f1(self):
print(self.name)

class Bar(metaclass=MyType):
def __init__(self, name):
self.name = name

def f1(self):
print(self.name)

#解释器解释
#1,遇到class Foo,执行type的__init__方法
#2,Type的init的方法里面做什么呢?不知道 C语言写的 无法修改
#3,执行Type的__call__方法
# 执行Foo类的__new__方法
# 执行Foo类的__init__方法

Mapper.register(Foo,"foo_123")
Mapper.register(Bar,"bar_123")

obj = Foo()
print(obj.name)
obj2 = Bar()
print(obj2.name)


C:\Python35\python.exe D:/py_django/test/a3.py
foo_123
bar_123

Process finished with exit code 0

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#依赖注入

class Mapper:
__mapper_relation = {}

@staticmethod
def register(cls,value):
Mapper.__mapper_relation[cls]=value

@staticmethod
def exist(cls):
if cls in Mapper.__mapper_relation:
return True
return False

@staticmethod
def value(cls):
return Mapper.__mapper_relation[cls]



class MyType(type):
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls,*args,**kwargs)
arg_list = list(args)
if Mapper.exist(cls):
value = Mapper.value(cls)
arg_list.append(value)
obj.__init__(*arg_list,**kwargs)
return obj


class BarFoo_parent:
def __init__(self):
pass

class Foo(metaclass=MyType):
def __init__(self,name):
self.name=name

def f1(self):
print(self.name)

class Bar(metaclass=MyType):
def __init__(self, name):
self.name = name

def f1(self):
print(self.name)

#解释器解释
#1,遇到class Foo,执行type的__init__方法
#2,Type的init的方法里面做什么呢?不知道 C语言写的 无法修改
#3,执行Type的__call__方法
# 执行Foo类的__new__方法
# 执行Foo类的__init__方法

Mapper.register(Foo,BarFoo_parent())
Mapper.register(Bar,Foo())

obj2 = Bar()
print(obj2)
print(obj2.name)
print(obj2.name.name)


C:\Python35\python.exe D:/py_django/test/a4.py
<__main__.Bar object at 0x0000000000714710>
<__main__.Foo object at 0x00000000007146D8>
<__main__.BarFoo_parent object at 0x0000000000714630>

Process finished with exit code 0

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8691816.html

posted on 2018-04-02 11:35  孙龙-程序员  阅读(642)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3