25.OOP II: Inheritance & Dunder Methods

Comprehensive Explanations

Object-Oriented Programming (OOP) in Python allows for the creation of classes and objects. Inheritance is a fundamental concept in OOP that enables a class (child class) to inherit attributes and methods from another class (parent class). Dunder methods (short for ‘double underscore’) are special methods in Python that begin and end with double underscores, such as __init__, __str__, and __add__. These methods allow customization of built-in behavior for objects.

Syntax and Multiple Examples

Example 1: Inheritance

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f'{self.name} makes a sound’

class Dog(Animal):
    def speak(self):
        return f'{self.name} barks’

dog = Dog(‘Buddy’)
print(dog.speak())  # Output: Buddy barks

Example 2: Dunder Methods

class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return f’Book: {self.title}’

book = Book(‘Python 101’)
print(book)  # Output: Book: Python 101

Table of Common List Methods

Method

Description

append()

Adds an element to the end of the list

extend()

Adds all elements of an iterable to the list

insert()

Inserts an element at a specific position

remove()

Removes the first occurrence of a value

pop()

Removes and returns element at given index

clear()

Removes all elements from the list

index()

Returns the index of the first occurrence

count()

Returns the number of occurrences of a value

sort()

Sorts the list in ascending order

reverse()

Reverses the order of the list

List Comprehensions

List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a for clause.

Example:
squares = [x**2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Nested Lists

Nested lists are lists within lists. They are useful for representing matrices or grids.

Example:
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[0])  # Output: [1, 2]
print(matrix[0][1])  # Output: 2

Best Practices

  • Use inheritance only when it makes logical sense.
  • Keep class definitions simple and focused.
  • Use dunder methods to customize object behavior.
  • Avoid deep inheritance hierarchies.
  • Use list comprehensions for cleaner and more readable code.
  • Document your classes and methods clearly.

 

Scroll to Top
Tutorialsjet.com