示例代碼:python
class MiNiCarStore(CarStore): def createCar(self, typeName): self.carFactory = CarFactory() # 會出現下劃線提示This inspection detects instance attribute definition outside __init__ method return self.carFactory.createCar(typeName)
緣由是:根據 SRP(Single Pesponsibility Principle, SRP) 原則,這個類原本就會承擔某個界面邏輯,那麼它就不該該再承擔「初始化」的職責,初始化的工做應該在另外一個單獨的類中完成,這樣能讓代碼更可測(也就是更好寫單元測試)數據庫
可改寫以下:緩存
class MiNiCarStore(CarStore): def __init__(self): self.carFactory = None def createCar(self, typeName): self.carFactory = CarFactory() return self.carFactory.createCar(typeName)
也能夠在settings -> editor -> inspections -> python 取消勾選提示ide
擴展閱讀單元測試
單一職責原則(Single Pesponsibility Principle, SRP)
單一職責有兩個含義: 一個是避免相同的職責分散到不一樣的類中, 別一個是避免一個類承擔太多職責
爲何要遵照SRP呢?測試