Python is an object-oriented programming language that supports the following key concepts:
1. Classes and Objects
- Class: A blueprint for creating objects. It defines attributes and methods that the objects of the class will have.
- Object: An instance of a class. It represents a real-world entity and has its own state and behavior.
2. Encapsulation
- Encapsulation is the mechanism that binds data (attributes) and methods (functions) together within a class.
- It restricts access to certain components of the object, protecting the data from external interference and misuse.
3. Inheritance
- Inheritance allows a class (child/subclass) to inherit attributes and methods from another class (parent/superclass).
- It promotes code reusability and helps in creating a hierarchy of classes.
4. Polymorphism
- Polymorphism allows objects of different classes to be treated as objects of a common superclass.
- It enables methods to be defined in multiple classes with the same name but different implementations.
5. Abstraction
- Abstraction hides the complex implementation details of a class and only reveals the necessary features to the outside world.
- It allows for creating abstract classes and methods that must be implemented by subclasses.
Example:
Below is an example demonstrating the use of classes and objects in Python:
python class Person: def __init__(self, name, age): self.name = name self.age = age def display_info(self): print(f"Name: {self.name}, Age: {self.age}") # Creating objects of the Person class person1 = Person("Alice", 30) person2 = Person("Bob", 25) # Accessing object attributes and methods person1.display_info() person2.display_info()In this example, the Person class defines attributes name and age along with a method display_info() to display the information of a person. Two objects person1 and person2 are created from the class and their details are displayed using the display_info() method.
No comments yet. Be the first to share your thoughts!