python 自定义type,依赖注入,solip设计原则

1.自定义type

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

class mytype(type):
    def __call__(self, *args, **kwargs):
        # 新建一个对象
        obj = self.__new__(self,*args,**kwargs)
        if self == Foo:
            print('此类为Foo')
            print('Foo  init 执行之前操作')
        obj.__init__(*args,**kwargs)
        return obj


class Foo(metaclass=mytype):
    def __init__(self):
        print('Foo init 操作')



object = Foo()

 

 2. self和cls只是python中约定的写法,本质上只是一个函数参数而已,没有特别含义。

           任何对象调用方法都会把把自己作为该方法中的第一个参数,传递到函数中。

 

3.依赖注入

#!/usr/bin/env python
# --*-- encoding: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
        else:
            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)
        args_list = list(args)
        if Mapper.exist(cls):
            value = Mapper.value(cls)
            args_list.append(value)
        obj.__init__( *args_list, **kwargs)
        return  obj

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

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

Mapper.register(Foo,'666')
Mapper.register(Bar,'999')

f = Foo()
print(f.name)
b = Bar()
print(b.name)

 

#!/usr/bin/env python
# --*-- encoding: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
        else:
            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)
        args_list = list(args)
        if Mapper.exist(cls):
            value = Mapper.value(cls)
            args_list.append(value)
        obj.__init__( *args_list, **kwargs)
        return  obj

class Tee():
    def __init__(self):
        pass

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

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

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

f = Foo()
print(f.t)
b = Bar()
print(b.f)

 

4.SOLIP 设计原则

  1.单一责任原则(SRP)

    一个对象应该只对一个元素负责

  2.开放封闭原则(OCP)

    对扩展开放,修改封闭

  3.里氏替换原则(LSP)

    可以使用任何派生类替换基类

  4.接口分离原则(ISP)

    对应接口进行分离避免一个接口的方法过多

  5.依赖倒置原则(DIP)

    隔离关系,使用接口或抽象类代指

  6.依赖注入(DI)和控制反转原则(ICO)

    使用钩子再原来执行流程中注入其他对象

 

    

posted @ 2017-07-03 23:03  1916  阅读(407)  评论(0)    收藏  举报