直接上代碼:app
Python Mixin(混入)這個功能,基本能夠解決抽象類的定義問題,好比說Java 裏定義抽象類的時候,須要定義一個抽象函數,Python若想實現這種抽象函數的話用Mixin就不用在寫抽象函數了,直接調用就行ide
# -*- coding:utf-8 -*- # 2016/8/29 # mail:ybs.kakashi@gmail.com class Coder(): def __init__(self, coder_type): print coder_type self.getIde() self.writecode() print "-----" * 10 def writecode(self): print "writing code happy with his ide!!!" class CPluseCoder(): def getIde(self): print "Use VS ide" class PythonCoder(): def getIde(self): print "Use PC ide" class SuperCoder(): def getIde(self): print "can Use TEXT and shit any other IDE" class JavaCoder(): def getIde(self): print "User Eclipse" class BaseCoder(): def getIde(self): print "asking which ide is the best! any where !!!" coder_dict = { "SuperCoder": SuperCoder, "PythonCoder": PythonCoder, "CPluseCoder": CPluseCoder, "JavaCoder": JavaCoder, "BaseCoder": BaseCoder } def get_coder(coder_name=None): Coder.__bases__ = (coder_dict.get(coder_name, BaseCoder),) if coder_name is None: coder_name = "Finder" return Coder(coder_name) get_coder("SuperCoder") get_coder("PythonCoder") get_coder("CPluseCoder") get_coder("JavaCoder") get_coder()
執行結果:函數
SuperCoder can Use TEXT and shit any other IDE writing code happy with his ide!!! -------------------------------------------------- PythonCoder Use PC ide writing code happy with his ide!!! -------------------------------------------------- CPluseCoder Use VS ide writing code happy with his ide!!! -------------------------------------------------- JavaCoder User Eclipse writing code happy with his ide!!! -------------------------------------------------- Finder asking which ide is the best! any where !!! writing code happy with his ide!!! -------------------------------------------------- Process finished with exit code 0