当前位置 : 主页 > 编程语言 > python >

python面向对象之依赖注入

来源:互联网 收集:自由互联 发布时间:2022-06-15
#!/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
#!/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

上一篇:python进程池高级版本
下一篇:没有了
网友评论