Posts

Showing posts with the label OOP

Polymorphism in Python

Image
Polymorphism in Python refers to the ability of objects to take on multiple forms or behaviors depending on the context in which they are used. It allows different objects to be treated as if they were of the same type, simplifying code and increasing flexibility. Method Overriding In Python, polymorphism is often achieved through method overriding or method overloading. Method overriding allows a subclass to provide a different implementation of a method that is already defined in its superclass: class ParentClass: def my_method(self): print("This is a method in the parent class") class ChildClass(ParentClass): def my_method(self): print("This is a method in the child class") my_object = ChildClass() my_object.my_method() # Output: This is a method in the child class In this example, the my_method() method in the subclass ChildClass overrides the method of the same name in the parent class ParentClass . Method Overload...

Classes and objects in Python

Image
Introduction to classes and objects Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint or template for creating objects, while an object is an instance of a class. Defining a class in Python In Python, a class is defined using the class keyword, followed by the name of the class and a colon. The class body contains attributes and methods: class MyClass: # class attributes attr1 = "Hello" attr2 = "World" # class method def my_method(self): print(self.attr1 + " " + self.attr2) Creating objects from a class To create an object from a class, you simply call the class as if it were a function: my_object = MyClass() Class attributes and instance attributes A class attribute is a variable that is shared by all instances of the class. An instance attribute is a variable that is unique to each instance of the class. You can access and modify class and in...