Tag Archives: This inspection detects instance attribute definition outside __init__ method

[Solved] Pycharm Warning: This inspection detects instance attribute definition outside __init__ method

Example code:

class MiNiCarStore(CarStore):

    def createCar(self, typeName):
        self.carFactory = CarFactory()  # An underline prompt will appear: This inspection detects instance attribute definition outside __init__ method
        return self.carFactory.createCar(typeName)

The reason is: according to the principle of SRP (single scalability principle, SRP), this class should assume a certain interface logic, so it should no longer assume the responsibility of “initialization”. The initialization work should be completed in a separate class, which can make the code more testable (that is, better write unit tests)

It can be rewritten as follows:

class MiNiCarStore(CarStore):
	
	def __init__(self):
        self.carFactory = None
        
    def createCar(self, typeName):
        self.carFactory = CarFactory()
        return self.carFactory.createCar(typeName)

You can also click Settings – > editor -> inspections -> Python uncheck prompt