Is Python a language that support object oriented?

Is Python a language that support object oriented?

Yes, Python is a fully object-oriented language. In Python, everything is an object, including numbers, strings, functions, and classes. Python supports all of the fundamental features of object-oriented programming (OOP), such as encapsulation, inheritance, and polymorphism.

Python's OOP capabilities are implemented through the use of classes and objects. A class is a blueprint for creating objects, which are instances of the class. A class can have attributes (data) and methods (functions), and it can inherit attributes and methods from other classes. Objects are created by calling the constructor of a class using the syntax object_name = class_name(), and methods can be called on objects using dot notation, like object_name.method_name().

Python also provides support for multiple inheritance, which allows a class to inherit from multiple parent classes. In addition, Python supports operator overloading, which allows classes to define how they respond to certain operators (such as + or -).

Overall, Python's object-oriented capabilities make it a powerful and flexible language for building complex software systems.

 

Show me the polymorphism in Python with code sample

Polymorphism is a key feature of object-oriented programming that allows objects of different classes to be treated as if they are objects of the same class. In Python, polymorphism can be demonstrated through method overriding, where a method in a subclass has the same name and parameters as a method in its superclass, but with a different implementation.

Here is an example of polymorphism in Python:

class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
        
    def area(self):
        return self.length * self.width

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
        
    def area(self):
        return 3.14 * self.radius ** 2

shapes = [Rectangle(2, 4), Circle(3)]
for shape in shapes:
    print(shape.area())

In this example, we define a superclass Shape with a method area that returns the area of the shape. We then define two subclasses, Rectangle and Circle, that inherit from Shape and override the area method with their own implementations.

In the main function, we create a list of Shape objects that includes both Rectangle and Circle objects. We then iterate over the list and call the area method on each object. Despite the fact that the area method is implemented differently in each subclass, we are able to call it in the same way on all objects of the Shape class, demonstrating polymorphism.

 

 

 

 

 

 

posted @ 2023-03-09 17:53  ChuckLu  阅读(22)  评论(0)    收藏  举报