https://zhuanlan.zhihu.com/p/28010894
https://www.zhihu.com/question/20021164python
@classmethod
@staticmethod編程
定義: 高層模塊不該該依賴低層模塊, 兩者都應該依賴其抽象, 抽象不該該依賴細節, 細節應該依賴抽象
問題由來: A直接依賴B, 若是將A改成依賴C, 則必須修改A的代碼,
解決方案: A改成依賴接口I, 類B和類C各自實現接口I, 類A經過接口I間接與類B或者類C發生聯繫函數
左後測試
區別在於當存在類的繼承的狀況下對多態的支持不一樣, OOP、多態上的意義 是什麼意思?spa
構造前的交互.net
依賴倒置原則: 核心在於面向接口編程code
https://blog.csdn.net/zhengzhb/article/details/7289269對象
媽媽講故事的例子:blog
Mother類
Book類
Newspaper類繼承
class Book{ public String getContent(){ return "好久好久之前有一個阿拉伯的故事……"; } } class Mother{ public void narrate(Book book){ System.out.println("媽媽開始講故事"); System.out.println(book.getContent()); } } public class Client{ public static void main(String[] args){ Mother mother = new Mother(); mother.narrate(new Book()); }
按照這樣的寫法, 若是將需求改成了讀報紙, 必需要修改mother類纔可以知足要求, 這其實很荒唐, 由於mother類能夠讀書卻不能讀報紙是不合邏輯的, 因此引入一個抽象的接口IReader
讀物, 只要是帶文字的都屬於讀物,書和報紙分別實現讀物接口, Mother類也和IReader
接口發生依賴關係, 這樣就符合依賴倒置原則。
class Newspaper implements IReader { public String getContent(){ return "今天是元旦新年"; } } class Book implements IReader{ public String getContent(){ return "好久之前..." } } class Mother { public void narrate(IReader reader){ System.out.println("媽媽開始講故事"); System.out.println(reader.getContent()); } } public class Client { public static void main(String[] args) { Mother mother = new Mother(); mother.narrate(new Book()); mother.narrate(new Newspaper()); } }
構造前交互 構造plugin 對象以前, 先從類中獲取必定的信息。
特殊構造函數
若是不引用任何類或者實例相關的屬性和方法, 只是單純經過傳入參數並返回數據的功能性方法, 那麼就適合用靜態方法來定義, 節省實例化對象的成本, 等同於在類外面的模塊層另寫一個函數
《Python Tricks》
class Pizza: def __init__(self, ingredients): self.ingredients = ingredients @classmethod def margherita(cls); return cls(['mozzarella', 'tomatoes']) @classmethod def prosciutto(cls); return cls(['mozzarella', 'tomatoes', 'ham'])
@classmethod
裏面定義的方法做用的對象是類, 使用cls
關鍵字, @staticmethod
關鍵字裏面調用的方法是
instance method裏面調用的方法是針對於某個實例, 使用self
關鍵字來鎖定
咱們能夠經過直接調用 Pizza.margherita()
來生成一個新的Pizza實例對象,
能夠將@classmethod
做爲構造器來使用,
ChainWarehouse
class Pizza: @staticmethod def circle_area(r); return r ** 2 * math.pi
Static Methods 是一個相對獨立的部分, circle_area()
不須要調用類中的屬性和方法, 這樣能夠避免修改致使低級錯誤, 更加易於測試
通常來講 classmethod能夠徹底替代staticmethod, 區別在於classmethod增長了一個對實際調用類的引用