python教程:mixin详解
1.什么是Mixin
在面向對象編程中,Mixin是一種類,這種類包含了其他類要使用的方法,但不必充當其他類的父類。其他類是如何獲取Mixin中的方法因語言的不同而不同。所以有時候Mixin被描述為’include’(包含)而不是 inheritance(繼承)。
Mixins鼓勵代碼重用,并且可以用于避免多重繼承可能導致(“如鉆石問題”)的繼承歧義,或者解決一個缺乏對一種語言的多重繼承的支持。mixin也可以被看作 實現方法 的接口。 這種模式是強制依賴性反轉原理的一個例子。
2.Mixin來源
mix-in是一種冰淇淋,提供一些基礎口味(香草,巧克力等),在這種基礎口味上可以添加其他食品(堅果,小餅干)。Mixin術語由此得來
3.定義及優點
Mixins是一種語言概念,允許程序員將一些代碼注入到一個類中。Mixin編程是一種軟件開發的風格,其中功能單元在一個類中創建,然后與其他類混合。
mixin類扮演父類的角色,包含其他類想要的功能。 然后,一個子類可以繼承或簡單地重用此功能,但不能作為專業化的手段。通常,mixin將會將所需的功能導出到子類中,而不會創建一個單一的“is a”關系。 這是mixins和繼承的概念之間的重要區別,因為子類仍然可以繼承父類的所有功能,但是,不必一定應用關于子對象“作為一種”父語義的語義。
優點
- 通過允許多個類使用通用功能,但沒有多重繼承的復雜語義,為多重繼承提供了一種機制.
- 代碼可重用性:當程序員希望在不同類之間共享功能時,Mixins很有用。 而不是一遍又一遍地重復相同的代碼,通用功能可以簡單地分組成一個混合,然后繼承到需要它的每個類中。
- Mixins允許繼承和使用只有父類的所需功能,不一定是父類的所有功能.
4.在python中的應用
在Python中,SocketServer模塊]具有UDPServer類和TCPServer類。它們分別作為UDP和TCP套接字服務器的服務器。 另外,還有兩個mixin類:ForkingMixIn和ThreadingMixIn。通常,所有新連接都在相同的過程中處理。 通過使用ThreadingMixIn擴展TCPServer,如下所示:
class ThreadingTCPServer(ThreadingMixIn, TCPServer):passThreadingMixIn類向TCP服務器添加功能,以便每個新連接創建一個新的線程。或者,使用ForkingMixIn將導致為每個新連接分叉進程。 顯然,創建新線程或分支進程的功能作為獨立類不是非常有用的。
在此使用示例中,mixins提供了替代底層功能,而不影響套接字服務器的功能。
5.在Django項目中的應用
Django TemplateView的實現代碼如下:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' class TemplateView(TemplateResponseMixin, ContextMixin, View):"""A view that renders a template. This view will also pass into the contextany keyword arguments passed by the URLconf."""def get(self, request, *args, **kwargs):context = self.get_context_data(**kwargs)return self.render_to_response(context)可以看到,這個視圖‘繼承了’TempalteResponseMixin,和ContextMixin以及View。
TempalteResponseMixin和ContextMixin實現分別如下:
class TemplateResponseMixin(object):"""A mixin that can be used to render a template."""template_name = Nonetemplate_engine = Noneresponse_class = TemplateResponsecontent_type = Nonedef render_to_response(self, context, **response_kwargs):"""Returns a response, using the `response_class` for thisview, with a template rendered with the given context.If any keyword arguments are provided, they will bepassed to the constructor of the response class."""response_kwargs.setdefault('content_type', self.content_type)return self.response_class(request=self.request,template=self.get_template_names(),context=context,using=self.template_engine,**response_kwargs)def get_template_names(self):"""Returns a list of template names to be used for the request. Must returna list. May not be called if render_to_response is overridden."""if self.template_name is None:raise ImproperlyConfigured("TemplateResponseMixin requires either a definition of ""'template_name' or an implementation of 'get_template_names()'")else:return [self.template_name]class ContextMixin(object):"""A default context mixin that passes the keyword arguments received byget_context_data as the template context."""def get_context_data(self, **kwargs):if 'view' not in kwargs:kwargs['view'] = selfreturn kwargs可以看到這兩個Mixin實際上只是為了給TemplatesView提供get_context_data和render_to_response兩個接口以及其他需要的數據,但這里并不適合把這兩個類解釋為TemplatesView的父類,而更傾向于解釋為提供接口及數據。把這兩個類封裝成mixin格式可以提高代碼的重用性,把這兩個類直接設計成函數我認為(個人見解,還 請指正)也是可以的,只不過這樣以來就不那么面向對象編程了。所以可以說Mixin應該是一種設計思想,并沒有什么獨特之處。至于好多類名字中為什么要加上Mixin,這只是為了提高代碼的可讀性而已。
總結
以上是生活随笔為你收集整理的python教程:mixin详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python调用其他文件中的函数或者类
- 下一篇: python教程:深copy浅copy