interface and Dependency Injection in Python

Source: Internet
Author: User

  First, we have to make it clear that there is no interface type in Python, and defining an interface is just an artificial rule, self-constraining in the programming process

    • A Python class can be written in any method.
    • Define an interface to constrain an inherited class, what methods are in the interface, what methods must be inherited from the class, the interface cannot have any function code
Class Interface:        def F1 (self):        "To do        something        : return:         ' class Something (Interface):        def F1 (self): "        print (' To-do something ... ')        def f2 (self):        print (" To-do ")

  In other languages, such as Java, the inheritance class does not rewrite the interface method will be error, and in Python does not, because Python does not have this type, so just a rule in our programming process, the class that begins with I is considered an interface

Class Iorderrepository:    def fetch_one_by (Self,nid):        Raise Exception (the method must be implemented in ' subclasses ') class Something ( Iorderrepository):    def fet_one_by (self,nid):        print (' Check data .... ')

Abstract classes, abstract methods
    • Abstract classes, which can be said to be a mixture of classes and interfaces, can either define a general method or constrain a subclass's method (abstract method)
Import abc# abstract class Foo (METACLASS=ABC. Abcmeta):    def F1 (self): print        (' F1 ')    #抽象方法    @abc. Abstractmethod    def f2 (self):        "        printing f2        ' class Bar (Foo):    def f2 (self):        print (' F2 ')    def f3 (self):        print (' F3 ') b = Bar () b.f1 () B.f2 () B.F3 ()

Dependency Injection

First, let's look at an ordinary class:

Class Foo:    def __init__ (self):        self.name = "Alex"        def F1 (self):        print (Self.name)
    • The first thing to be clear is that in Python, everything is an object.
    • All classes are objects, and by default they are created by type

To create a class execution flow:

    • Encounter class keyword, execute type __init__ method, create Foo class object
    • Executes the __call__ method in the type in the instance of the instantiated object (Obj=foo ())
    1. Invoke the __new__ method of the Foo class in the call method (responsible for creating the object)
    2. Execute the __init__ method of the Foo class (Initialize)

Knowing how it works, we can make a fuss in the __call__.

Class MyType (Type):    def __call__ (Cls,*args,**kwargs):        obj = cls.__new__ (Cls,*args,**kwargs)        print (' In the face of this: ')        Print (' ========================== ')        print (' Bite me ')        obj.__init__ (*args,**kwargs)        return objclass Foo (metaclass=mytype):    def __init__ (self):        self.name = ' alex ' F = Foo () print (f.name)

If I were to be skilled in applying dependency injection, I would also understand the concept that combination: The purpose of a combination is to decouple, reduce dependencies, and change to a specific value or object into the interior to be passed in as a parameter.

For example, when an instance bar object is wrapped, the Foo object is encapsulated, and the instance Foo object encapsulates the head object, which is passed to the constructor in the form of a parameter.

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 get_value (CLS): Return MAPPER.__MAPPER_RELATION[CLS] Class MyType (type): Def __call__ (cls,*args,**kwargs): obj = cls.__new__ (cls,*args,**kwargs) arg_list = Li St (args) if Mapper.exist (CLS): value = Mapper.get_value (CLS) arg_list.append (value) OB j.__init__ (*arg_list,**kwargs) return objclass head:def __init__ (self): Self.name = ' Alex ' class Foo (meta Class=mytype): Def __init__ (self,h): self.h = h def f1 (self): print (Self.h) class Bar (Metaclass=mytype) : Def __init__ (self,f): Self.f = f def f2 (self): print (SELF.F) mapper.register (Foo,head ()) mapper.regist ER (Bar,foo ()) b = Bar () prInt (B.F) 

interface and Dependency Injection in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.