python解耦
1、需要使用很多不同类中的方法
定义一个虚拟类,让这个借口类继承这些类,然后只需要引用这个接口类就可以了。
class Foo1(): def chi(self): print "chi" class Foo2(): def he(self): print "he" #接口类 class Fooo(Foo1,Foo2): def func_far(self): print "func1" def indexf(Fatherobj): class shui(Fatherobj): def haichi(self): print "haichi" shuii = shui() shuii.chi() indexf(Fooo) >>> chi >>>
2、需要定义一个随时能调用不同接口类的函数或类
如果程序将入参类写为固定,那么这个调用类就和其他的类耦合程度太大,不利于维护。
class Foo1(): def foo1(self): print "foo1" class Foo2(): def foo2(self): print "foo2" class Ft(): def __init__(self,Foo2): self.f = Foo2() def exef(self): self.f.foo2() ft = Ft(Foo2) ft.exef()
解耦
class Foo1(): def foo1(self): print "foo1" class Foo2(): def foo2(self): print "foo2" #Foo2换为一个变量,objc。 class Ft(): def __init__(self,objc): self.f = objc() def exef(self): self.f.foo2() ft = Ft(Foo2) ft.exef()
3、需要入参为某个类型
不建议入参写为固定某个类型,这时需要定义一个上层接口,作为入参的所有接口都继承这个接口类,入参同样只需要输入这个接口类即可。
程序不一定正确只是说明先继承父类的若干子类,然后再入参设置为父类
#上层接口类 class Fooo(): def func_far(self): print "func1" class Foo1(Fooo): def chi(self): print "chi" class Foo2(Fooo): def he(self): print "he" def indexf(Fatherobj): class shui(Fatherobj): def haichi(self): print "haichi" shuii = shui() shuii.chi() indexf(Fooo)
。