Skip to content

Magic Methods & CLI Arguments

1. Magic Methods (Dunder Methods)

Magic methods in Python are the methods having two underscores prefix and suffix in their name. They are commonly called dunder methods (Double Underscore).

Examples: __init__, __str__, __len__, __add__.

Example: Customizing String Representation

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"'{self.title}' by {self.author}"

b = Book("Python Basics", "VD")
print(b) # Uses __str__ to print: 'Python Basics' by VD

2. Command Line Arguments

Sometimes you want to pass information into your script when you run it from the terminal.

Using sys.argv (Simple)

import sys

# Run as: python script.py Vishnu
print(f"Hello, {sys.argv[1]}")

Using argparse (Professional)

import argparse

parser = argparse.ArgumentParser(description="Greet a user.")
parser.add_index("--name", help="The name of the user")
args = parser.parse_args()

print(f"Hello, {args.name}")

Industry Context

Almost all professional backend scripts and CLI tools (like git or mkdocs) use command line arguments to control their behavior.