This principle state that the Class should have only one responsibility.
Code That violates SRP is:
classPerson:def__init__(self,name,age):self.name=nameself.age=agedefgreet(self):print(f"Hello, my name is {self.name} and I'm {self.age} years old.")defcelebrate_birthday(self):self.age+=1print(f"{self.name} is now {self.age} years old!")
In the above code, the Person class have two responsibility one is to greet and another one is to celebrate a birthday to follow the SRP create a different class one which handles greeting and the other handles birthday celebration.
classPerson:def__init__(self,name,age):self.name=nameself.age=agedefgreet(self):print(f"Hello, my name is {self.name} and I'm {self.age} years old.")classBirthdayCelebrator:defcelebrate_birthday(self,person):person.age+=1print(f"{person.name} is now {person.age} years old!")
The Open-Closed Principle (OCP)
This principle states that the class should be closed for modification but open for extension.
This principle states that the object created using the child class can replace the object created using The parent class.
Code that violates LSP is:
classBird:deffly(self):print("The bird is flying")classPenguin(Bird):deffly(self):raiseException("I can't fly")defmake_bird_fly(bird):bird.fly()bird=Bird()make_bird_fly(bird)# Output: The bird is flying
penguin=Penguin()make_bird_fly(penguin)# Output: An exception is raised
In the above code, the penguin will raise the error when we call the fly method. To correct it simply do method ovveridding.
classBird:deffly(self):print("The bird is flying")classPenguin(Bird):deffly(self):print("I can't fly")defmake_bird_fly(bird):bird.fly()bird=Bird()make_bird_fly(bird)# Output: The bird is flying
penguin=Penguin()make_bird_fly(penguin)# output: I can't fly
Interface Segregation Principle (ISP)
This principle states that it is better to have many small, specific interfaces, rather than one large, general-purpose interface.
Code that violates ISP is:
fromabcimportABC,abstractmethodclassAnimal(ABC):@abstractmethoddefeat(self):pass@abstractmethoddefsleep(self):pass@abstractmethoddefmove(self):passclassDog(Animal):defeat(self):print("The dog is eating")defsleep(self):print("The dog is sleeping")defmove(self):print("The dog is running")
Above code violates the ISP as if we try to create a fish class using an animal class but it doesn't have ability to move so we need to create methods which are common in all animals such as eating, sleep, and reproduction.
above method is common in all animals hence it is the simplest interface for animals and another method will be added according to other animals in their class.
Dependency Inversion Principle (DIP)
This principle state that Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.
Top comments (0)