Inheritance
Inheritance is an important concept in Object-Oriented Programming (OOP) that allows you to create a new class by inheriting the attributes and methods of an existing class. The existing class is known as the parent class, while the new class is known as the child class. The child class inherits all the properties of the parent class, and it can also have its own unique properties.
The syntax for creating a child class in Python is as follows:
class ChildClass(ParentClass):
# child class definition
In this example, ChildClass is the name of the child class, and ParentClass is the name of the parent class that it inherits from. The child class definition goes inside the class definition block, just like with any other class definition.
Let's look at an example to see how inheritance works in Python. Suppose we have a Person class that has two attributes: name and age, and a method called greet that prints a greeting message. We can define the Person class as follows:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}, and I am {self.age} years old.")
Now, let's create a child class called Student that inherits from the Person class. The Student class will have an additional attribute called major and a method called study that prints a message about what the student is studying. We can define the Student class as follows:
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def study(self):
print(f"I am studying {self.major}.")
In this example, we used the super() function to call the __init__() method of the parent class (Person) and pass in the name and age arguments. We also defined a new attribute called major that is unique to the Student class. Finally, we defined a new method called study that is unique to the Student class.
Now, let's create an instance of the Student class and call its methods:
s = Student("John", 20, "Computer Science")
s.greet() # prints "Hello, my name is John, and I am 20 years old."
s.study() # prints "I am studying Computer Science."
As you can see, the Student class inherited the greet() method from the Person class, and it also has its own unique method called study().
Conclusion
nheritance is a powerful feature of Python that allows you to create new classes by reusing code from existing classes. By inheriting from a parent class, a child class can have all the attributes and methods of the parent class, as well as its own unique attributes and methods. This makes it easier to organize and maintain complex codebases, and it promotes code reuse and modularity.
Basic Topics
- Introduction to Python
- Basic Syntax and Data Types
- Variables and Operators
- Input
- Conditional statements
- Loops
- Functions
- List
- Tuples
- Sets
- Dictionary
- Modules
- Packages
- Exception Handling
- Read/Write Files