#!/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