vue项目接口域名动态的获取方法
357
2022-09-04
python面向对象之依赖注入
#!/usr/bin/env python# -*- coding: utf-8 -*-
# 组合# a = a()# b = b(a)# c = c(b)# d = d(c)
#依赖注入class Mapper: __mapper_relation = {}@staticmethoddef register(cls,value): Mapper.__mapper_relation[cls]=value@staticmethoddef exist(cls):if cls in Mapper.__mapper_relation:return True return False@staticmethoddef 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 objclass Foo(metaclass=MyType):def __init__(self,name):self.name=namedef f1(self):print(self.name)class Bar(metaclass=MyType):def __init__(self, name):self.name = namedef 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 = {}@staticmethoddef register(cls,value): Mapper.__mapper_relation[cls]=value@staticmethoddef exist(cls):if cls in Mapper.__mapper_relation:return True return False@staticmethoddef 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 objclass BarFoo_parent:def __init__(self):passclass Foo(metaclass=MyType):def __init__(self,name):self.name=namedef f1(self):print(self.name)class Bar(metaclass=MyType):def __init__(self, name):self.name = namedef 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
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~