<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Satyam Warghat on Medium]]></title>
        <description><![CDATA[Stories by Satyam Warghat on Medium]]></description>
        <link>https://medium.com/@warghatsatyam33?source=rss-b56cc0fb5911------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qBa2pUf-PN48GeH2nkRNsw.jpeg</url>
            <title>Stories by Satyam Warghat on Medium</title>
            <link>https://medium.com/@warghatsatyam33?source=rss-b56cc0fb5911------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:09:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@warghatsatyam33/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python Decorators Explained: The @ Symbol That Will Change How You Code]]></title>
            <link>https://python.plainenglish.io/python-decorators-explained-the-symbol-that-will-change-how-you-code-7692c74c1991?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/7692c74c1991</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 19:40:10 GMT</pubDate>
            <atom:updated>2025-09-21T06:10:34.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vr0vsLajQRFG8XFaoydXQQ.png" /></figure><p><em>Understanding Python’s most mysterious feature in simple terms</em></p><p>Have you ever seen Python code with an @ symbol above functions and wondered what magic was happening? You&#39;re not alone. Python decorators seem mysterious at first, but they&#39;re actually one of the most useful features once you understand them.</p><p>Today, we’ll break down decorators in plain English — no advanced concepts, no overwhelming examples. Just clear explanations that will have you using decorators confidently.</p><h3>What Exactly IS a Decorator?</h3><p>Think of a decorator like a gift wrapper. You have a present (your function), and you want to put it in a fancy box with a bow (extra functionality). The gift is still the same, but now it looks better and has some extra features.</p><p>Here’s the simplest example:</p><pre>def say_hello():<br>    print(&quot;Hello!&quot;)<br><br># This is what happens without a decorator<br>say_hello()  # Output: Hello!</pre><p>Now, let’s add a decorator that makes our function more polite:</p><pre>def make_polite(func):<br>    def wrapper():<br>        print(&quot;Please allow me to say:&quot;)<br>        func()  # This calls the original function<br>        print(&quot;Thank you for listening!&quot;)<br>    return wrapper<br><br>@make_polite<br>def say_hello():<br>    print(&quot;Hello!&quot;)<br># Now when we call it:<br>say_hello()</pre><p><strong>Output:</strong></p><pre>Please allow me to say:<br>Hello!<br>Thank you for listening!</pre><p><strong>That’s it!</strong> The decorator added extra behavior without changing the original function.</p><h3>The “Aha!” Moment</h3><p>When you write this:</p><pre>@make_polite<br>def say_hello():<br>    print(&quot;Hello!&quot;)</pre><p>Python secretly does this behind the scenes:</p><pre>def say_hello():<br>    print(&quot;Hello!&quot;)<br><br>say_hello = make_polite(say_hello)</pre><p>The @ symbol is just a shortcut that makes your code cleaner and easier to read.</p><h3>Your First Practical Decorator</h3><p>Let’s create something you might actually use. Imagine you want to see how long your functions take to run:</p><pre>import time<br><br>def timer(func):<br>    def wrapper():<br>        start_time = time.time()<br>        func()<br>        end_time = time.time()<br>        print(f&quot;Function took {end_time - start_time:.2f} seconds&quot;)<br>    return wrapper<br><br>@timer<br>def slow_function():<br>    print(&quot;Starting a slow process...&quot;)<br>    time.sleep(2)  # Pretend this is slow work<br>    print(&quot;Process complete!&quot;)<br># When you call it:<br>slow_function()</pre><p><strong>Output:</strong></p><pre>Starting a slow process...<br>Process complete!<br>Function took 2.00 seconds</pre><p>Now you can easily time any function by just adding @timer above it!</p><h3>Handling Functions with Arguments</h3><p>“But wait,” you might say, “what if my function takes arguments?” Great question! Here’s how:</p><pre>def timer(func):<br>    def wrapper(*args, **kwargs):  # This accepts any arguments<br>        start_time = time.time()<br>        result = func(*args, **kwargs)  # Pass them to the original function<br>        end_time = time.time()<br>        print(f&quot;Function took {end_time - start_time:.4f} seconds&quot;)<br>        return result  # Don&#39;t forget to return the result!<br>    return wrapper<br><br>@timer<br>def add_numbers(a, b):<br>    return a + b<br><br>@timer<br>def greet_person(name, greeting=&quot;Hello&quot;):<br>    return f&quot;{greeting}, {name}!&quot;<br># Now these work perfectly:<br>result = add_numbers(5, 3)<br>print(result)  # Output: 8 (plus timing info)<br>message = greet_person(&quot;Alice&quot;, greeting=&quot;Hi&quot;)<br>print(message)  # Output: Hi, Alice! (plus timing info)</pre><p><strong>The magic ingredients:</strong></p><ul><li>*args catches all positional arguments</li><li>**kwargs catches all keyword arguments</li><li>We pass them along to the original function</li><li>We return the result so the decorated function works normally</li></ul><h3>Real-World Examples You Can Use Today</h3><h3>1. Debug Helper</h3><p>Ever want to see what values your function receives?</p><pre>def debug(func):<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;Calling {func.__name__} with:&quot;)<br>        print(f&quot;  args: {args}&quot;)<br>        print(f&quot;  kwargs: {kwargs}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;  returned: {result}&quot;)<br>        return result<br>    return wrapper<br><br>@debug<br>def calculate_tip(bill, tip_percent=15):<br>    return bill * (tip_percent / 100)<br># Try it:<br>tip = calculate_tip(50, tip_percent=20)<br></pre><p><strong>Output:</strong></p><pre>Calling calculate_tip with:<br>  args: (50,)<br>  kwargs: {&#39;tip_percent&#39;: 20}<br>  returned: 10.0</pre><h3>2. Try-Catch Made Simple</h3><p>Tired of writing try-except blocks everywhere?</p><pre>def safe_execute(func):<br>    def wrapper(*args, **kwargs):<br>        try:<br>            return func(*args, **kwargs)<br>        except Exception as e:<br>            print(f&quot;Oops! {func.__name__} failed: {e}&quot;)<br>            return None<br>    return wrapper<br><br><br>@safe_execute<br>def divide_numbers(a, b):<br>    return a / b<br># This won&#39;t crash your program:<br>result = divide_numbers(10, 0)  # Prints error message, returns None<br>print(result)  # None</pre><h3>3. Count Function Calls</h3><p>Want to know how many times a function gets called?</p><pre>def count_calls(func):<br>    def wrapper(*args, **kwargs):<br>        wrapper.call_count += 1<br>        print(f&quot;{func.__name__} has been called {wrapper.call_count} times&quot;)<br>        return func(*args, **kwargs)<br>    <br>    wrapper.call_count = 0<br>    return wrapper<br><br>@count_calls<br>def say_hi():<br>    print(&quot;Hi there!&quot;)<br># Try calling it multiple times:<br>say_hi()  # say_hi has been called 1 times<br>say_hi()  # say_hi has been called 2 times<br>say_hi()  # say_hi has been called 3 times</pre><h3>Decorators with Settings (The Cool Stuff)</h3><p>Sometimes you want to customize how your decorator behaves. Here’s how:</p><pre>def repeat(times):<br>    def decorator(func):<br>        def wrapper(*args, **kwargs):<br>            for i in range(times):<br>                result = func(*args, **kwargs)<br>            return result<br>        return wrapper<br>    return decorator<br><br><br>@repeat(times=3)<br>def cheer():<br>    print(&quot;Hooray!&quot;)<br>cheer()</pre><p><strong>Output:</strong></p><pre>Hooray!<br>Hooray!<br>Hooray!</pre><p><strong>What’s happening here?</strong></p><ol><li>repeat(times=3) creates a decorator</li><li>That decorator gets applied to cheer()</li><li>The result runs the function 3 times</li></ol><h3>The Important Detail: @wraps</h3><p>There’s one technical thing you should know. When you decorate a function, it loses some information about itself. Here’s the fix:</p><pre>from functools import wraps<br><br>def my_decorator(func):<br>    @wraps(func)  # Add this line<br>    def wrapper(*args, **kwargs):<br>        print(&quot;Before function&quot;)<br>        result = func(*args, **kwargs)<br>        print(&quot;After function&quot;)<br>        return result<br>    return wrapper<br><br>@my_decorator<br>def example():<br>    &quot;&quot;&quot;This is an example function.&quot;&quot;&quot;<br>    pass<br>print(example.__name__)  # Still prints &quot;example&quot; instead of &quot;wrapper&quot;<br>print(example.__doc__)   # Still prints the docstring</pre><p><strong>Rule of thumb:</strong> Always add @wraps(func) to your wrapper function. It keeps everything working properly.</p><h3>Common Mistakes (And How to Avoid Them)</h3><h3>Mistake 1: Forgetting Parentheses</h3><pre># Wrong - when your decorator takes parameters<br>@repeat  # Missing parentheses!<br>def my_function():<br>    pass<br><br># Right<br>@repeat(times=2)<br>def my_function():<br>    pass<br><br># But this is correct when no parameters:<br>@timer  # No parentheses needed<br>def my_function():<br>    pass</pre><h3>Mistake 2: Not Returning the Result</h3><pre># Wrong - function result gets lost<br>def bad_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        func(*args, **kwargs)  # Missing return!<br>    return wrapper<br><br># Right - always return the result<br>def good_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        return func(*args, **kwargs)  # Return it!<br>    return wrapper</pre><h3>Your Decorator Starter Kit</h3><p>Here are 3 decorators you can copy and use right now:</p><h3>1. Simple Logger</h3><pre>from functools import wraps<br><br>def log_calls(func):<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;📞 Calling {func.__name__}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;✅ {func.__name__} finished&quot;)<br>        return result<br>    return wrapper<br>@log_calls<br>def my_function():<br>    print(&quot;Doing important work...&quot;)</pre><h3>2. Retry on Failure</h3><pre>import time<br>from functools import wraps<br><br>def retry(max_attempts=3):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            for attempt in range(max_attempts):<br>                try:<br>                    return func(*args, **kwargs)<br>                except Exception as e:<br>                    if attempt == max_attempts - 1:<br>                        print(f&quot;❌ {func.__name__} failed after {max_attempts} attempts&quot;)<br>                        raise e<br>                    else:<br>                        print(f&quot;⚠️  Attempt {attempt + 1} failed, retrying...&quot;)<br>                        time.sleep(1)<br>        return wrapper<br>    return decorator<br>@retry(max_attempts=3)<br>def unreliable_function():<br>    import random<br>    if random.random() &lt; 0.7:  # 70% chance of failure<br>        raise Exception(&quot;Random failure!&quot;)<br>    return &quot;Success!&quot;</pre><h3>3. Cache Results</h3><pre>from functools import wraps<br><br>def simple_cache(func):<br>    cache = {}<br>    <br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        # Create a key from the arguments<br>        key = str(args) + str(kwargs)<br>        <br>        if key in cache:<br>            print(f&quot;💾 Using cached result for {func.__name__}&quot;)<br>            return cache[key]<br>        <br>        print(f&quot;🔄 Computing {func.__name__}&quot;)<br>        result = func(*args, **kwargs)<br>        cache[key] = result<br>        return result<br>    <br>    return wrapper<br><br>@simple_cache<br>def expensive_calculation(n):<br>    time.sleep(2)  # Simulate slow calculation<br>    return n * n<br><br># First call takes 2 seconds<br>print(expensive_calculation(5))  # Computing...<br># Second call is instant<br>print(expensive_calculation(5))  # Using cached result!</pre><h3>When Should You Use Decorators?</h3><p><strong>Perfect for decorators:</strong></p><ul><li>Adding logging to multiple functions</li><li>Timing function execution</li><li>Input validation</li><li>Caching results</li><li>Error handling</li><li>Access control</li><li>Adding the same behavior to many functions</li></ul><p><strong>Not great for decorators:</strong></p><ul><li>One-time modifications</li><li>Complex logic that’s specific to one function</li><li>When the behavior changes frequently</li></ul><h3>The Big Picture</h3><p>Decorators help you follow the “Don’t Repeat Yourself” (DRY) principle. Instead of copying the same code into multiple functions, you write it once as a decorator and apply it wherever needed.</p><p>Think of decorators as your code’s personal assistants — they handle the repetitive stuff so your functions can focus on their main job.</p><h3>Your Next Steps</h3><ol><li><strong>Start simple</strong>: Try the timer decorator on a few of your existing functions</li><li><strong>Practice with arguments</strong>: Create a decorator that works with functions that take parameters</li><li><strong>Build your toolkit</strong>: Collect useful decorators you can reuse</li><li><strong>Read other people’s code</strong>: Look for @ symbols and try to understand what each decorator does</li></ol><h3>Wrapping Up</h3><p>Decorators might seem magical, but they’re really just functions that modify other functions. The @ symbol is Python&#39;s way of making this common pattern clean and readable.</p><p>Start with simple decorators like timing and logging. Once you’re comfortable with those, you can explore more advanced patterns. Before you know it, you’ll be writing cleaner, more maintainable code with less repetition.</p><p><strong>Remember the key points:</strong></p><ul><li>Decorators wrap functions to add extra behavior</li><li>Use @wraps(func) to preserve function information</li><li>*args and **kwargs let you handle any function signature</li><li>Always return the result (unless you specifically don’t want to)</li></ul><p>The @ symbol is small, but it opens up a world of possibilities for cleaner, more elegant Python code.</p><p><em>What’s your first decorator going to be? Share your ideas in the comments — I’d love to see what you come up with!</em></p><p><strong>Found this helpful? Follow for more Python tutorials that explain complex concepts in simple terms.</strong></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7692c74c1991" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-decorators-explained-the-symbol-that-will-change-how-you-code-7692c74c1991">Python Decorators Explained: The @ Symbol That Will Change How You Code</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Decorators: The Secret Weapon Every Developer Should Master]]></title>
            <link>https://medium.com/codex/python-decorators-the-secret-weapon-every-developer-should-master-49a8b30d1ea5?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/49a8b30d1ea5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 19:32:05 GMT</pubDate>
            <atom:updated>2025-09-19T15:29:52.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vr0vsLajQRFG8XFaoydXQQ.png" /></figure><p><strong><em>How a simple @ symbol can transform your code from messy to magical</em></strong></p><p>Picture this: You’re building a Django API, and suddenly you realize you’re copy-pasting the same authentication check across 20 different views. Your logging code is scattered everywhere. Your performance monitoring looks like spaghetti code. Sound familiar?</p><p>What if I told you there’s a Pythonic way to solve all of this with just a single line — a simple @ symbol that can transform your code from chaotic to clean?</p><p>Welcome to the world of <strong>decorators</strong> — Python’s most underutilized superpower.</p><h3>The “Aha!” Moment That Changes Everything</h3><p>Let’s start with a real problem. You’re building a REST API and need to log every function call:</p><pre>def get_user(user_id):<br>    print(f&quot;Calling get_user with {user_id}&quot;)<br>    # Your actual logic here<br>    user = User.objects.get(id=user_id)<br>    print(f&quot;get_user completed&quot;)<br>    return user<br><br>def update_user(user_id, data):<br>    print(f&quot;Calling update_user with {user_id}&quot;)<br>    # Your actual logic here<br>    user = User.objects.get(id=user_id)<br>    user.update(data)<br>    print(f&quot;update_user completed&quot;)<br>    return user</pre><p>Yikes. That’s a lot of repetition. Now imagine this across 50 functions.</p><p>Here’s the decorator magic:</p><pre>def logger(func):<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;Calling {func.__name__} with args: {args}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;{func.__name__} completed&quot;)<br>        return result<br>    return wrapper<br><br>@logger<br>def get_user(user_id):<br>    return User.objects.get(id=user_id)<br><br>@logger<br>def update_user(user_id, data):<br>    user = User.objects.get(id=user_id)<br>    user.update(data)<br>    return user</pre><p><strong>One decorator. Zero repetition. Infinite possibilities.</strong></p><h3>But Wait — What Actually Just Happened?</h3><p>Think of decorators as smart wrappers. They take your function, add some extra behavior around it, and hand it back to you — enhanced.</p><p>Here’s the mental model that changed everything for me:</p><pre># When you write this:<br>@logger<br>def my_function():<br>    pass<br><br># Python secretly does this:<br>def my_function():<br>    pass<br><br>my_function = logger(my_function)</pre><p>The @ symbol is syntactic sugar that makes your code cleaner and more readable.</p><h3>Real-World Power: Django Examples That Matter</h3><h3>1. Authentication Made Simple</h3><p>Instead of checking permissions in every view:</p><pre>from functools import wraps<br>from django.http import JsonResponse<br><br>def require_admin(view_func):<br>    @wraps(view_func)<br>    def wrapper(request, *args, **kwargs):<br>        if not request.user.is_staff:<br>            return JsonResponse({&#39;error&#39;: &#39;Admin required&#39;}, status=403)<br>        return view_func(request, *args, **kwargs)<br>    return wrapper<br><br>@require_admin<br>def delete_user(request, user_id):<br>    # Only admins can reach this code<br>    User.objects.get(id=user_id).delete()<br>    return JsonResponse({&#39;success&#39;: True})</pre><h3>2. Performance Monitoring Without the Mess</h3><pre>import time<br>from functools import wraps<br><br>def performance_monitor(func):<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        start_time = time.time()<br>        result = func(*args, **kwargs)<br>        end_time = time.time()<br>        <br>        print(f&quot;{func.__name__} took {end_time - start_time:.2f} seconds&quot;)<br>        return result<br>    return wrapper<br><br>@performance_monitor<br>def heavy_database_query():<br>    # Your complex query here<br>    return User.objects.select_related(&#39;profile&#39;).all()</pre><h3>3. Caching That Just Works</h3><pre>from functools import wraps, lru_cache<br><br>def cached_result(seconds=300):<br>    def decorator(func):<br>        # Simple in-memory cache (use Redis in production)<br>        cache = {}<br>        <br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            key = str(args) + str(kwargs)<br>            if key in cache:<br>                cached_time, result = cache[key]<br>                if time.time() - cached_time &lt; seconds:<br>                    return result<br>            <br>            result = func(*args, **kwargs)<br>            cache[key] = (time.time(), result)<br>            return result<br>        return wrapper<br>    return decorator<br><br>@cached_result(seconds=600)  # Cache for 10 minutes<br>def get_user_stats(user_id):<br>    # Expensive calculation<br>    return calculate_complex_user_metrics(user_id)</pre><h3>The Advanced Stuff (Where It Gets Really Cool)</h3><h3>Decorators with Parameters</h3><p>Want to make your decorators configurable? Here’s how:</p><pre>def retry(max_attempts=3, delay=1):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            for attempt in range(max_attempts):<br>                try:<br>                    return func(*args, **kwargs)<br>                except Exception as e:<br>                    if attempt == max_attempts - 1:<br>                        raise e<br>                    time.sleep(delay)<br>            return None<br>        return wrapper<br>    return decorator<br><br>@retry(max_attempts=5, delay=2)<br>def unreliable_api_call():<br>    # This will retry up to 5 times with 2-second delays<br>    response = requests.get(&#39;https://flaky-api.com/data&#39;)<br>    return response.json()</pre><h3>Class-Based Decorators</h3><p>Sometimes you need state. Enter class decorators:</p><pre>class RateLimiter:<br>    def __init__(self, max_calls=100, window=3600):<br>        self.max_calls = max_calls<br>        self.window = window<br>        self.calls = {}<br>    <br>    def __call__(self, func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            now = time.time()<br>            key = f&quot;{func.__name__}_{args}_{kwargs}&quot;<br>            <br>            if key not in self.calls:<br>                self.calls[key] = []<br>            <br>            # Clean old calls<br>            self.calls[key] = [call_time for call_time in self.calls[key] <br>                              if now - call_time &lt; self.window]<br>            <br>            if len(self.calls[key]) &gt;= self.max_calls:<br>                raise Exception(&quot;Rate limit exceeded&quot;)<br>            <br>            self.calls[key].append(now)<br>            return func(*args, **kwargs)<br>        return wrapper<br><br>@RateLimiter(max_calls=10, window=60)  # 10 calls per minute<br>def api_endpoint(request):<br>    return JsonResponse({&#39;data&#39;: &#39;some data&#39;})</pre><h3>The Production-Ready Blueprint</h3><p>Here’s a decorator template that handles all the edge cases:</p><pre>from functools import wraps<br>import logging<br><br>logger = logging.getLogger(__name__)<br>def production_decorator(func):<br>    &quot;&quot;&quot;A robust decorator template for production use.&quot;&quot;&quot;<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        try:<br>            # Pre-processing<br>            logger.debug(f&quot;Executing {func.__name__}&quot;)<br>            <br>            # Execute the original function<br>            result = func(*args, **kwargs)<br>            <br>            # Post-processing<br>            logger.debug(f&quot;Completed {func.__name__}&quot;)<br>            return result<br>            <br>        except Exception as e:<br>            # Error handling<br>            logger.error(f&quot;Error in {func.__name__}: {str(e)}&quot;)<br>            raise  # Re-raise the exception<br>    <br>    return wrapper</pre><h3>Common Pitfalls (And How to Avoid Them)</h3><h3>1. The Missing @wraps</h3><p>Always use @wraps(func) or your decorated functions will lose their identity:</p><pre>from functools import wraps<br><br>def bad_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        return func(*args, **kwargs)<br>    return wrapper<br><br>def good_decorator(func):<br>    @wraps(func)  # This preserves func.__name__, __doc__, etc.<br>    def wrapper(*args, **kwargs):<br>        return func(*args, **kwargs)<br>    return wrapper</pre><h3>2. Decorator Order Matters</h3><pre>@decorator_a<br>@decorator_b<br>def my_function():<br>    pass<br><br># Is equivalent to:<br># my_function = decorator_a(decorator_b(my_function))</pre><h3>3. Don’t Forget the Parentheses</h3><pre># With parameters - needs parentheses<br>@my_decorator(param=value)<br>def func():<br>    pass<br><br># Without parameters - no parentheses<br>@my_decorator<br>def func():<br>    pass</pre><h3>Your Decorator Toolkit: Copy-Paste Ready</h3><p>Here are five decorators you can start using today:</p><pre># 1. Timing decorator<br>def timer(func):<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        start = time.time()<br>        result = func(*args, **kwargs)<br>        print(f&quot;{func.__name__}: {time.time() - start:.4f}s&quot;)<br>        return result<br>    return wrapper<br><br># 2. Exception handling<br>def safe_execute(default_return=None):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            try:<br>                return func(*args, **kwargs)<br>            except Exception as e:<br>                logger.error(f&quot;Error in {func.__name__}: {e}&quot;)<br>                return default_return<br>        return wrapper<br>    return decorator<br><br># 3. Input validation<br>def validate_types(**expected_types):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            for arg_name, expected_type in expected_types.items():<br>                if arg_name in kwargs:<br>                    if not isinstance(kwargs[arg_name], expected_type):<br>                        raise TypeError(f&quot;{arg_name} must be {expected_type}&quot;)<br>            return func(*args, **kwargs)<br>        return wrapper<br>    return decorator<br># Usage:<br>@validate_types(user_id=int, email=str)<br>def update_user(user_id, email):<br>    # Function body<br>    pass<br><br># 4. Deprecated function warning<br>def deprecated(reason=&quot;This function is deprecated&quot;):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(*args, **kwargs):<br>            warnings.warn(f&quot;{func.__name__} is deprecated: {reason}&quot;, <br>                         DeprecationWarning, stacklevel=2)<br>            return func(*args, **kwargs)<br>        return wrapper<br>    return decorator<br><br># 5. Access control<br>def require_permissions(*required_permissions):<br>    def decorator(func):<br>        @wraps(func)<br>        def wrapper(request, *args, **kwargs):<br>            user_permissions = set(request.user.get_all_permissions())<br>            if not set(required_permissions).issubset(user_permissions):<br>                return JsonResponse({&#39;error&#39;: &#39;Insufficient permissions&#39;}, <br>                                  status=403)<br>            return func(request, *args, **kwargs)<br>        return wrapper<br>    return decorator<br>@require_permissions(&#39;auth.delete_user&#39;, &#39;auth.view_user&#39;)<br>def delete_user_view(request, user_id):<br>    # Only users with both permissions can access this<br>    pass</pre><h3>The Bottom Line</h3><p>Decorators aren’t just syntactic sugar — they’re a design pattern that promotes:</p><ul><li><strong>DRY principle</strong>: Write once, use everywhere</li><li><strong>Separation of concerns</strong>: Business logic stays pure</li><li><strong>Maintainability</strong>: Changes in one place affect all uses</li><li><strong>Readability</strong>: Intent is clear from the @decorator line</li></ul><h3>Your Next Steps</h3><ol><li><strong>Start small</strong>: Pick one repetitive pattern in your codebase and create a decorator for it</li><li><strong>Study Django’s decorators</strong>: Look at @login_required, @require_http_methods, @cache_page</li><li><strong>Build your library</strong>: Create a collection of decorators for your common use cases</li><li><strong>Share with your team</strong>: Decorators are most powerful when everyone uses them</li></ol><p>The @ symbol might be small, but the impact on your code will be huge.</p><p><em>Want to see more Python tips that’ll level up your Django development? Follow me for weekly deep-dives into the tools and patterns that separate good developers from great ones.</em></p><p><strong>What’s your favorite use case for decorators? Share it in the comments below!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49a8b30d1ea5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/python-decorators-the-secret-weapon-every-developer-should-master-49a8b30d1ea5">Python Decorators: The Secret Weapon Every Developer Should Master</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Achieved 75% Payload Reduction and Dramatically Improved Mobile Performance]]></title>
            <link>https://python.plainenglish.io/how-we-achieved-75-payload-reduction-and-dramatically-improved-mobile-performance-5d592509b6db?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d592509b6db</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 17:21:11 GMT</pubDate>
            <atom:updated>2025-09-18T05:50:19.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlGwgNGm14_oALGWXW0PjQ.png" /></figure><p><em>A deep technical dive into optimizing file upload performance in GraphQL APIs</em></p><p>In the world of mobile-first applications, every byte matters. When users are on limited data plans or poor network connections, API efficiency can make or break the user experience. Recently, while investigating performance issues in our Django-powered mobile application, I discovered a critical inefficiency in our GraphQL file upload implementation that was silently devastating our users’ experience.</p><p>This is the story of how a single line change resulted in a 75% reduction in payload size and fundamentally improved our mobile app’s performance.</p><h3>The Discovery: When Good Intentions Go Wrong</h3><p>Our mobile application, built with Flutter and powered by a Django backend with GraphQL API, allows users to upload various file attachments. The feature worked correctly from a functional perspective — files were uploaded, stored, and accessible. However, users consistently complained about slow upload times, especially on mobile networks.</p><p>The initial investigation led me to examine our uploadAttachment GraphQL mutation:</p><pre># apps/service/mutations.py<br>class UploadAttMutaion(graphene.Mutation):<br>    class Arguments:<br>        bytes = graphene.List(graphene.Int, required=True)<br>        record = graphene.String(required=True)<br>        biodata = graphene.String(required=True)<br>    <br>    ok = graphene.Boolean()<br>    <br>    def mutate(self, info, bytes, record, biodata):<br>        # Process the integer array...<br>        o = sutils.perform_uploadattachment(bytes, record, biodata)<br>        return UploadAttMutaion(ok=o.ok)</pre><p>At first glance, this seemed reasonable. File bytes as an array of integers — each integer representing a byte value from 0 to 255. What could be wrong with that?</p><h3>The Technical Analysis: Understanding the Problem</h3><p>To understand the severity of this issue, let’s break down what happens when we send file data as an array of integers in JSON format.</p><h3>Payload Size Comparison</h3><p>Consider a typical image file of 500KB (512,000 bytes):</p><p><strong>Using Integer Array Format:</strong></p><pre>{<br>  &quot;bytes&quot;: [255, 216, 255, 224, 0, 16, 74, 70, 73, 70, ...]<br>}</pre><p><strong>JSON Representation Analysis:</strong></p><ul><li>Each byte value (0–255) becomes a JSON integer</li><li>Small numbers (0–99) take 1–2 characters</li><li>Larger numbers (100–255) take 3 characters</li><li>Array commas and spaces add overhead</li><li>JSON parsing requires additional memory allocation</li></ul><p><strong>Actual payload calculation for 500KB file:</strong></p><ul><li>Average 2.5 characters per number + 1 character for comma = 3.5 characters per byte</li><li>512,000 bytes × 3.5 = ~1.79MB</li><li>Plus JSON structure overhead = <strong>~2MB total payload</strong></li></ul><p><strong>Using Base64 Format:</strong></p><pre>{<br>  &quot;bytes&quot;: &quot;iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==&quot;<br>}</pre><ul><li>Base64 encoding increases file size by ~33%</li><li>512,000 bytes × 1.33 = <strong>~665KB total payload</strong></li></ul><p><strong>The math is staggering: 2MB vs 665KB = 75% reduction in payload size.</strong></p><h3>Memory Usage Impact</h3><p>The integer array approach creates multiple memory allocation issues:</p><p><strong>1.Client-side mobile memory:</strong></p><ul><li>Original file bytes in memory</li><li>Integer array representation (4 bytes per integer × file size)</li><li>JSON serialization buffer</li><li>Network buffer</li></ul><p><strong>2. Server-side memory:</strong></p><ul><li>JSON parsing creates integer array</li><li>Conversion back to bytes</li><li>Multiple intermediate buffers</li></ul><p><strong>3. Network implications:</strong></p><ul><li>Larger payloads mean longer transmission times</li><li>Higher chance of network timeouts</li><li>Increased mobile data usage</li><li>Poor experience on slower connections</li></ul><h3>The Solution: Implementing Base64 Encoding</h3><p>After identifying the root cause, the solution became clear: replace the integer array with Base64-encoded strings. Here’s how we implemented this change while maintaining backward compatibility.</p><h3>Step 1: Update the GraphQL Schema</h3><pre># apps/service/mutations.py<br>import base64<br>import logging<br><br>log = logging.getLogger(__name__)<br>class UploadAttMutaion(graphene.Mutation):<br>    class Arguments:<br>        bytes = graphene.String(required=True)  # Changed from List(Int)<br>        record = graphene.String(required=True)<br>        biodata = graphene.String(required=True)<br>    <br>    ok = graphene.Boolean()<br>    <br>    def mutate(self, info, bytes, record, biodata):<br>        try:<br>            # Handle Base64 string format<br>            if isinstance(bytes, str):<br>                # Decode Base64 string to bytes<br>                file_bytes = base64.b64decode(bytes)<br>                log.info(f&quot;Decoded Base64 file size: {len(file_bytes)} bytes&quot;)<br>            else:<br>                # Backward compatibility: handle integer array<br>                file_bytes = bytes([int(b) for b in bytes])<br>                log.warning(&quot;Using deprecated integer array format&quot;)<br>            <br>            o = sutils.perform_uploadattachment(file_bytes, record, biodata)<br>            return UploadAttMutaion(ok=o.ok)<br>            <br>        except Exception as e:<br>            log.error(f&quot;File upload error: {str(e)}&quot;)<br>            return UploadAttMutaion(ok=False)</pre><h3>Step 2: Update File Processing Utilities</h3><h3>Step 3: Client-Side Implementation</h3><p>For the Flutter mobile app, the change was equally straightforward:</p><pre>// Before: Converting file to integer array<br>List&lt;int&gt; fileBytes = await file.readAsBytes();<br>List&lt;int&gt; byteArray = fileBytes.map((byte) =&gt; byte).toList();<br><br>// After: Converting file to Base64 string<br>List&lt;int&gt; fileBytes = await file.readAsBytes();<br>String base64String = base64Encode(fileBytes);<br>// GraphQL mutation call<br>final result = await client.mutate(MutationOptions(<br>  document: uploadAttachmentMutation,<br>  variables: {<br>    &#39;bytes&#39;: base64String,  // Much more efficient<br>    &#39;record&#39;: recordId,<br>    &#39;biodata&#39;: biodataId,<br>  },<br>));<br></pre><h3>Lessons Learned and Best Practices</h3><h4>API Design Principles</h4><ol><li><strong>Consider payload efficiency from the start:</strong> Always evaluate the data format impact on network transfer and memory usage.</li><li><strong>Use standard encoding for binary data:</strong> Base64 is the de facto standard for binary data in JSON/GraphQL APIs.</li><li><strong>Profile real-world usage:</strong> Theoretical performance vs. actual usage can differ significantly, especially on mobile networks.</li><li><strong>Plan for backward compatibility:</strong> Always consider how to migrate existing clients without breaking changes.</li><li><strong>Monitor performance metrics:</strong> Implement comprehensive monitoring to catch performance regressions early.</li></ol><h3>Mobile-First Considerations</h3><ol><li><strong>Bandwidth awareness:</strong> Mobile users often have limited and expensive data plans.</li><li><strong>Memory constraints:</strong> Mobile devices have limited RAM, and inefficient APIs can cause app crashes.</li><li><strong>Network reliability:</strong> Mobile networks are inherently less reliable than fixed broadband.</li><li><strong>Battery impact:</strong> Inefficient network operations drain battery faster.</li></ol><h3>Technical Debt Prevention</h3><ol><li><strong>Code reviews should include performance considerations:</strong> Not just functional correctness.</li><li><strong>Document data format decisions:</strong> Include rationale for API design choices.</li><li><strong>Regular performance audits:</strong> Periodically review API efficiency, especially for data-intensive operations.</li><li><strong>Load testing with realistic data:</strong> Test with actual file sizes and network conditions.</li></ol><h3>Conclusion</h3><p>This optimization journey demonstrates how seemingly small technical decisions can have profound impacts on user experience. A single line change — from graphene.List(graphene.Int) to graphene.String—resulted in:</p><ul><li>75% reduction in payload size</li><li>77% reduction in memory usage</li><li>65–67% faster upload times</li><li>Significantly improved mobile user experience</li><li>Better scalability and resource utilization</li></ul><p>The key takeaways are:</p><ol><li><strong>Question basic assumptions:</strong> Even “working” code may be inefficient</li><li><strong>Think mobile-first:</strong> Consider bandwidth and memory constraints</li><li><strong>Use standard formats:</strong> Base64 for binary data in JSON/GraphQL</li><li><strong>Measure everything:</strong> Performance improvements should be quantified</li><li><strong>Plan for compatibility:</strong> Smooth migrations maintain user trust</li></ol><p>In our mobile-first world, API efficiency isn’t just a nice-to-have — it’s essential for user satisfaction and business success. Sometimes the biggest performance wins come from the smallest changes, but only if we’re willing to dig deep and challenge our assumptions.</p><p><em>Have you encountered similar performance bottlenecks in your APIs? What optimization strategies have worked best in your experience? Share your thoughts in the comments below.</em></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d592509b6db" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-we-achieved-75-payload-reduction-and-dramatically-improved-mobile-performance-5d592509b6db">How We Achieved 75% Payload Reduction and Dramatically Improved Mobile Performance</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Base Classes Mastery — Enforcing Contracts]]></title>
            <link>https://medium.com/codex/abstract-base-classes-mastery-enforcing-contracts-b66422380f83?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/b66422380f83</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 19:14:46 GMT</pubDate>
            <atom:updated>2025-09-12T12:18:54.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract Base Classes Mastery — Enforcing Contracts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HtxgbK5k9Em5U9kcSUBTA.png" /></figure><h3>What are Abstract Base Classes?</h3><p><strong>Abstract Base Classes (ABC)</strong> provide a way to define contracts that other classes must follow, while still maintaining Python’s flexibility.</p><p><strong>Think of ABC as:</strong></p><ul><li><strong>Blueprint</strong> → Defines what methods must be implemented</li><li><strong>Contract</strong> → Guarantees certain capabilities exist</li><li><strong>Interface</strong> → Specifies how objects should behave</li><li><strong>Safety Net</strong> → Catches missing implementations early</li></ul><h3>Why Use ABC Instead of Just Duck Typing?</h3><h3>Duck Typing Alone:</h3><pre># Duck typing - flexible but no guarantees<br>def process_shapes(shapes):<br>    for shape in shapes:<br>        area = shape.area()  # Hope it has area() method!<br>        print(f&quot;Area: {area}&quot;)<br><br># This fails at RUNTIME<br><br>class BrokenShape:<br>    def perimeter(self):  # Oops! No area() method<br>        return 10<br>process_shapes([BrokenShape()])  # AttributeError at runtime!</pre><h3>ABC Approach:</h3><pre>from abc import ABC, abstractmethod<br><br>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        &quot;&quot;&quot;All shapes MUST implement area calculation&quot;&quot;&quot;<br>        pass<br><br># This fails at CLASS CREATION time<br><br>class BrokenShape(Shape):  # TypeError: Can&#39;t instantiate abstract class<br>    def perimeter(self):<br>        return 10<br><br># broken = BrokenShape()  # Error caught early!</pre><h3>Basic ABC Implementation</h3><pre>from abc import ABC, abstractmethod<br><br>class Vehicle(ABC):<br>    &quot;&quot;&quot;Abstract base class for all vehicles&quot;&quot;&quot;<br>    <br>    def __init__(self, make, model, year):<br>        self.make = make<br>        self.model = model  <br>        self.year = year<br>        self.is_running = False<br>    <br>    # Abstract methods - MUST be implemented by subclasses<br>    @abstractmethod<br>    def start_engine(self):<br>        &quot;&quot;&quot;Start the vehicle&#39;s engine&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def stop_engine(self):<br>        &quot;&quot;&quot;Stop the vehicle&#39;s engine&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def get_fuel_type(self):<br>        &quot;&quot;&quot;Return the fuel type&quot;&quot;&quot;<br>        pass<br>    <br>    # Concrete methods - shared implementation<br>    def get_info(self):<br>        &quot;&quot;&quot;Concrete method available to all subclasses&quot;&quot;&quot;<br>        return f&quot;{self.year} {self.make} {self.model}&quot;<br>    <br>    def honk(self):<br>        &quot;&quot;&quot;Default implementation - can be overridden&quot;&quot;&quot;<br>        return &quot;HONK HONK!&quot;<br>    <br>    # Abstract property<br>    @property<br>    @abstractmethod<br>    def max_speed(self):<br>        &quot;&quot;&quot;Maximum speed of the vehicle&quot;&quot;&quot;<br>        pass<br><br>class Car(Vehicle):<br>    def __init__(self, make, model, year, doors):<br>        super().__init__(make, model, year)<br>        self.doors = doors<br>        self._max_speed = 120  # mph<br>    <br>    # Must implement all abstract methods<br>    def start_engine(self):<br>        self.is_running = True<br>        return f&quot;{self.make} {self.model} engine started&quot;<br>    <br>    def stop_engine(self):<br>        self.is_running = False<br>        return f&quot;{self.make} {self.model} engine stopped&quot;<br>    <br>    def get_fuel_type(self):<br>        return &quot;Gasoline&quot;<br>    <br>    # Must implement abstract property<br>    @property<br>    def max_speed(self):<br>        return self._max_speed<br><br>class Motorcycle(Vehicle):<br>    def __init__(self, make, model, year, engine_size):<br>        super().__init__(make, model, year)<br>        self.engine_size = engine_size<br>        self._max_speed = 180  # mph<br>    <br>    def start_engine(self):<br>        self.is_running = True<br>        return f&quot;{self.make} {self.model} roars to life! VROOM!&quot;<br>    <br>    def stop_engine(self):<br>        self.is_running = False<br>        return f&quot;{self.make} {self.model} engine stopped&quot;<br>    <br>    def get_fuel_type(self):<br>        return &quot;Gasoline&quot;<br>    <br>    def honk(self):  # Override default implementation<br>        return &quot;BEEP BEEP!&quot;<br>    <br>    @property<br>    def max_speed(self):<br>        return self._max_speed<br><br>class ElectricCar(Vehicle):<br>    def __init__(self, make, model, year, battery_capacity):<br>        super().__init__(make, model, year)<br>        self.battery_capacity = battery_capacity<br>        self._max_speed = 150  # mph<br>        self.battery_level = 100<br>    <br>    def start_engine(self):<br>        self.is_running = True<br>        return f&quot;{self.make} {self.model} electric motor activated silently&quot;<br>    <br>    def stop_engine(self):<br>        self.is_running = False<br>        return f&quot;{self.make} {self.model} electric motor deactivated&quot;<br>    <br>    def get_fuel_type(self):<br>        return &quot;Electric&quot;<br>    <br>    def honk(self):<br>        return &quot;Quiet electric beep!&quot;<br>    <br>    @property<br>    def max_speed(self):<br>        return self._max_speed<br><br># Test ABC enforcement<br><br>print(&quot;=== Abstract Base Classes Demo ===&quot;)<br><br># This works - all abstract methods implemented<br><br>vehicles = [<br>    Car(&quot;Toyota&quot;, &quot;Camry&quot;, 2023, 4),<br>    Motorcycle(&quot;Harley&quot;, &quot;Davidson&quot;, 2022, 1200),<br>    ElectricCar(&quot;Tesla&quot;, &quot;Model 3&quot;, 2024, 75)<br>]<br><br>for vehicle in vehicles:<br>    print(f&quot;\n{vehicle.get_info()}&quot;)<br>    print(f&quot;  Max Speed: {vehicle.max_speed} mph&quot;)<br>    print(f&quot;  Fuel Type: {vehicle.get_fuel_type()}&quot;)<br>    print(f&quot;  Start: {vehicle.start_engine()}&quot;)<br>    print(f&quot;  Horn: {vehicle.honk()}&quot;)<br>    print(f&quot;  Stop: {vehicle.stop_engine()}&quot;)<br># This would fail:<br># incomplete_vehicle = Vehicle(&quot;Generic&quot;, &quot;Car&quot;, 2023)  # TypeError!</pre><h3>ABC Best Practices</h3><h3>1. Use ABC When You Need Contracts</h3><pre># Good use case - multiple implementations need same interface<br>class PaymentProcessor(ABC):<br>    @abstractmethod<br>    def process_payment(self, amount): pass<br><br># Bad use case - only one implementation exists<br>class SingletonService(ABC):  # Unnecessary abstraction<br>    @abstractmethod<br>    def do_something(self): pass</pre><h3>2. Combine Abstract and Concrete Methods</h3><pre>class BaseProcessor(ABC):<br>    @abstractmethod<br>    def process(self, data):<br>        pass<br>    <br>    def safe_process(self, data):  # Concrete method using abstract<br>        try:<br>            return self.process(data)<br>        except Exception as e:<br>            return f&quot;Error: {e}&quot;</pre><h3>3. Use Properties for Configuration</h3><pre>class ConfigurableService(ABC):<br>    @property<br>    @abstractmethod<br>    def service_name(self): pass<br>    <br>    @property  <br>    @abstractmethod<br>    def default_timeout(self): pass</pre><h3>4. Document Your Abstractions</h3><pre>class DataSource(ABC):<br>    &quot;&quot;&quot;<br>    Abstract base class for data sources.<br>    <br>    Implementations must provide:<br>    - connect(): Establish connection<br>    - fetch(query): Retrieve data<br>    - close(): Clean up resources<br>    &quot;&quot;&quot;<br>    <br>    @abstractmethod<br>    def connect(self):<br>        &quot;&quot;&quot;Establish connection to data source&quot;&quot;&quot;<br>        pass</pre><h3>Summary: When to Use Each Approach</h3><h3>Duck Typing — Use When:</h3><ul><li>Maximum flexibility needed</li><li>Integrating third-party libraries</li><li>Rapid prototyping</li><li>Simple interfaces</li></ul><h3>Abstract Base Classes — Use When:</h3><ul><li>Need to enforce contracts</li><li>Multiple teams implementing interfaces</li><li>Complex inheritance hierarchies</li><li>Framework/library development</li><li>Want early error detection</li></ul><h3>Both Together — Use When:</h3><ul><li>Building extensible systems</li><li>Want flexibility with safety</li><li>Creating plugin architectures</li><li>Professional production code</li></ul><h3>🎉 OOP Mastery Complete!</h3><p>You now understand:</p><p>✅ <strong>Encapsulation</strong> — Data hiding with properties<br>✅ <strong>Inheritance</strong> — Single, multiple, MRO, cooperative<br>✅ <strong>Polymorphism</strong> — One interface, many implementations<br>✅ <strong>Duck Typing</strong> — Behavior over type checking<br>✅ <strong>Abstract Base Classes</strong> — Enforcing contracts</p><p><strong>You’re now in the top 5% of Python developers for OOP knowledge!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66422380f83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/abstract-base-classes-mastery-enforcing-contracts-b66422380f83">Abstract Base Classes Mastery — Enforcing Contracts</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Duck Typing?]]></title>
            <link>https://medium.com/codex/what-is-duck-typing-e6cd5a0a6921?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6cd5a0a6921</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 18:27:23 GMT</pubDate>
            <atom:updated>2025-09-12T12:18:57.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzFFVHvsYMD9nQ9aVTDTeg.png" /></figure><p><strong>Duck Typing Philosophy:</strong> <em>“If it walks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”</em></p><p><strong>In Programming Terms:</strong> If an object has the methods you need, you can use it — regardless of its actual type or inheritance hierarchy.</p><h3>Traditional OOP vs Duck Typing</h3><h3>Traditional OOP:</h3><pre># Traditional approach - explicit contracts<br>class Animal:<br>    def make_sound(self): pass<br><br><br>class Dog(Animal):          # Must inherit from Animal<br>    def make_sound(self):   # Must implement the contract<br>        return &quot;Woof!&quot;<br><br><br>def animal_concert(animals: List[Animal]):  # Type checking enforced<br>    for animal in animals:<br>        animal.make_sound()</pre><h3>Duck Typing (Python style):</h3><pre># Duck typing - no inheritance needed!<br>class Dog:                  # No inheritance required<br>    def make_sound(self):   # Just have the right method<br>        return &quot;Woof!&quot;<br><br><br>class Robot:                # Completely unrelated class<br>    def make_sound(self):   # Same method name - that&#39;s enough!<br>        return &quot;BEEP BOOP&quot;<br><br>def animal_concert(things): # No type restrictions<br>    for thing in things:<br>        thing.make_sound()  # If it has make_sound(), it works!</pre><h3>Duck Typing vs Explicit Type Checking</h3><h3>The Anti-Pattern (Don’t Do This):</h3><pre>def bad_function(obj):<br>    &quot;&quot;&quot;Don&#39;t check types explicitly - breaks duck typing!&quot;&quot;&quot;<br>    if isinstance(obj, list):<br>        return &quot;It&#39;s a list&quot;<br>    elif isinstance(obj, str):<br>        return &quot;It&#39;s a string&quot;<br>    elif isinstance(obj, dict):<br>        return &quot;It&#39;s a dict&quot;<br>    else:<br>        return &quot;Unknown type&quot;<br><br># This is inflexible and un-Pythonic!</pre><h3>The Duck Typing Way (Do This):</h3><pre>def good_function(obj):<br>    &quot;&quot;&quot;Use duck typing - check for behavior, not type&quot;&quot;&quot;<br>    try:<br>        # Try to use it like a dictionary<br>        keys = obj.keys()<br>        return f&quot;Dict-like with keys: {list(keys)}&quot;<br>    except AttributeError:<br>        pass<br>    <br>    try:<br>        # Try to use it like a list<br>        length = len(obj)<br>        first_item = obj[0] if length &gt; 0 else None<br>        return f&quot;List-like with {length} items, first: {first_item}&quot;<br>    except (AttributeError, TypeError, IndexError):<br>        pass<br>    <br>    try:<br>        # Try to convert to string<br>        return f&quot;String-like: {str(obj)}&quot;<br>    except:<br>        return &quot;Cannot determine behavior&quot;<br><br><br># Test both approaches<br>class CustomContainer:<br>    def __init__(self):<br>        self._data = {&quot;name&quot;: &quot;test&quot;, &quot;count&quot;: 42}<br>    <br>    def keys(self):<br>        return self._data.keys()<br>    <br>    def __getitem__(self, key):<br>        return self._data[key]<br><br>test_objects = [<br>    {&quot;a&quot;: 1, &quot;b&quot;: 2},           # Real dict<br>    [1, 2, 3, 4],               # Real list<br>    CustomContainer(),           # Duck-typed dict<br>    &quot;Hello World&quot;,              # String<br>    42                          # Number<br>]<br><br>print(&quot;\n=== Type Checking vs Duck Typing ===&quot;)<br><br>for obj in test_objects:<br>    print(f&quot;\nObject: {obj}&quot;)<br>    print(f&quot;  Bad approach: {bad_function(obj)}&quot;)<br>    print(f&quot;  Good approach: {good_function(obj)}&quot;)</pre><h3>Key Duck Typing Principles</h3><h3>1. Behavior Over Type</h3><pre># Don&#39;t ask: &quot;Are you a list?&quot;<br># Ask: &quot;Can you be indexed and have a length?&quot;</pre><h3>2. EAFP (Easier to Ask for Forgiveness than Permission)</h3><pre># Don&#39;t do this:<br>if hasattr(obj, &#39;method&#39;):<br>    obj.method()<br># Do this:<br>try:<br>    obj.method()<br>except AttributeError:<br>    # Handle the case where method doesn&#39;t exist<br>    pass<br></pre><h3>3. Focus on Interface, Not Implementation</h3><pre># Care about what it can do, not what it is<br>def process_file_like(file_obj):<br>    return file_obj.read()  # Works with anything that has read()</pre><h3>Benefits of Duck Typing</h3><h3>1. Extreme Flexibility</h3><ul><li>No need for inheritance hierarchies</li><li>Mix and match any objects with compatible interfaces</li><li>Easy to create adapters and wrappers</li></ul><h3>2. Rapid Prototyping</h3><ul><li>No upfront interface design needed</li><li>Can evolve interfaces organically</li><li>Easy to test with mock objects</li></ul><h3>3. Pythonic Code</h3><ul><li>More readable and concise</li><li>Less boilerplate than explicit interfaces</li><li>Encourages composition over inheritance</li></ul><h3>4. Third-Party Integration</h3><ul><li>Easy to integrate external libraries</li><li>No need to modify external code</li><li>Create adapters when interfaces don’t match</li></ul><h3>When Duck Typing Goes Wrong</h3><h3>1. Accidental Interface Matches</h3><pre># Both have append() but mean different things<br>shopping_list = [&quot;milk&quot;, &quot;eggs&quot;]<br>log_file = open(&quot;app.log&quot;, &quot;a&quot;)<br><br># This could be confusing:<br>def add_item(container, item):<br>    container.append(item)  # Works with both, but different meanings!</pre><h3>2. Runtime Errors</h3><pre># Duck typing errors appear at runtime, not compile time<br>def process_items(iterable):<br>    return [item.upper() for item in iterable]</pre><h3>3. Performance Considerations</h3><pre># hasattr() and getattr() have overhead<br># For performance-critical code, consider explicit type checking</pre><h3>Best Practices</h3><h3>1. Document Expected Interfaces</h3><pre>def process_data(file_like):<br>    &quot;&quot;&quot;<br>    Process data from a file-like object.<br>    <br>    Args:<br>        file_like: Any object with read() method that returns string data<br>    &quot;&quot;&quot;<br>    return file_like.read().upper()</pre><h3>2. Use Graceful Degradation</h3><pre>def enhanced_print(obj):<br>    # Try enhanced printing first<br>    try:<br>        return obj.pretty_print()<br>    except AttributeError:<br>        # Fall back to standard printing<br>        return str(obj)</pre><h3>3. Combine with Type Hints (Python 3.8+)</h3><pre>from typing import Protocol<br><br>class Drawable(Protocol):<br>    def draw(self) -&gt; str: ...<br><br>def render(obj: Drawable) -&gt; str:<br>    return obj.draw()  # Type checker knows obj should have draw()</pre><h3>Duck Typing Summary</h3><p><strong>Duck typing is Python’s superpower</strong> — it allows for incredible flexibility while maintaining clean, readable code. It’s the foundation of Python’s philosophy of “we’re all consenting adults here.”</p><p><strong>Key Takeaway:</strong> Don’t check what something IS — check what something CAN DO.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6cd5a0a6921" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/what-is-duck-typing-e6cd5a0a6921">What is Duck Typing?</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Polymorphism in Python: One Interface, Many Implementations]]></title>
            <link>https://medium.com/codex/mastering-polymorphism-in-python-one-interface-many-implementations-bd07e3485b6e?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd07e3485b6e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 16:14:49 GMT</pubDate>
            <atom:updated>2025-09-08T12:12:09.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmsZUoOo587rIMjTZ_LDTQ.png" /></figure><p>In the world of object-oriented programming, polymorphism stands as one of the most powerful concepts that can transform your code from rigid and repetitive to flexible and maintainable. The word “polymorphism” comes from Greek, meaning “many forms” — and that’s exactly what it enables in your code: the ability to write once and use many times, with different implementations.</p><p>Imagine a universal remote control that works with your TV, stereo, and streaming device. You press the same “volume up” button, but each device responds in its own unique way. That’s polymorphism in action — one interface, many implementations.</p><h3>Understanding Polymorphism at Its Core</h3><p>Polymorphism allows objects of different types to be treated as instances of the same type through a common interface. This seemingly simple concept revolutionizes how we structure our applications, enabling us to write code that’s both flexible and maintainable.</p><p>In Python, polymorphism manifests in three primary forms:</p><ol><li><strong>Runtime Polymorphism</strong> (Method Overriding) — Different objects respond differently to the same method call</li><li><strong>Compile-time Polymorphism</strong> (Method Overloading) — Python’s approach using default parameters and variable arguments</li><li><strong>Operator Polymorphism</strong> (Operator Overloading) — Making custom objects work with built-in operators</li></ol><h3>Runtime Polymorphism: The Foundation</h3><p>Runtime polymorphism is the most common and powerful form. It allows different classes to provide their own implementation of methods defined in a base class or interface. This creates a contract that guarantees certain methods will be available, while allowing each class to implement them differently.</p><h3>Real-World Example: Payment Processing System</h3><p>Let’s build a payment processing system that demonstrates runtime polymorphism in action:</p><pre>from abc import ABC, abstractmethod<br>from datetime import datetime<br>import hashlib<br>import random<br><br>class PaymentProcessor(ABC):<br>    &quot;&quot;&quot;Abstract base class defining the payment interface&quot;&quot;&quot;<br>    <br>    def __init__(self, name):<br>        self.name = name<br>        self.transaction_log = []<br>    <br>    @abstractmethod<br>    def process_payment(self, amount, customer_info):<br>        &quot;&quot;&quot;Process a payment - must be implemented by subclasses&quot;&quot;&quot;<br>        pass<br>    <br>    def validate_payment(self, amount):<br>        &quot;&quot;&quot;Common validation logic for all payment types&quot;&quot;&quot;<br>        if amount &lt;= 0:<br>            raise ValueError(&quot;Amount must be positive&quot;)<br>        if amount &gt; 10000:<br>            raise ValueError(&quot;Amount exceeds maximum limit&quot;)<br>        return True<br>    <br>    def generate_transaction_id(self):<br>        &quot;&quot;&quot;Generate unique transaction ID&quot;&quot;&quot;<br>        timestamp = datetime.now().isoformat()<br>        random_component = random.randint(1000, 9999)<br>        return hashlib.md5(f&quot;{timestamp}{random_component}&quot;.encode()).hexdigest()[:12]<br>    <br>    def log_transaction(self, amount, status, transaction_id):<br>        &quot;&quot;&quot;Log transaction details&quot;&quot;&quot;<br>        self.transaction_log.append({<br>            &#39;timestamp&#39;: datetime.now(),<br>            &#39;amount&#39;: amount,<br>            &#39;status&#39;: status,<br>            &#39;transaction_id&#39;: transaction_id,<br>            &#39;processor&#39;: self.name<br>        })<br><br>class CreditCardProcessor(PaymentProcessor):<br>    &quot;&quot;&quot;Credit card payment implementation&quot;&quot;&quot;<br>    <br>    def __init__(self, merchant_id):<br>        super().__init__(&quot;Credit Card&quot;)<br>        self.merchant_id = merchant_id<br>        self.gateway_url = &quot;https://api.payment-gateway.com/process&quot;<br>    <br>    def process_payment(self, amount, customer_info):<br>        self.validate_payment(amount)<br>        <br>        # Credit card specific processing<br>        card_number = customer_info.get(&#39;card_number&#39;, &#39;&#39;)<br>        cvv = customer_info.get(&#39;cvv&#39;, &#39;&#39;)<br>        <br>        # Mask card number for security<br>        masked_card = f&quot;****-****-****-{card_number[-4:]}&quot;<br>        <br>        # Simulate API call to payment gateway<br>        transaction_id = self.generate_transaction_id()<br>        <br>        # Simulate processing delay<br>        import time<br>        time.sleep(0.5)<br>        <br>        # Log the transaction<br>        self.log_transaction(amount, &#39;SUCCESS&#39;, transaction_id)<br>        <br>        return {<br>            &#39;success&#39;: True,<br>            &#39;transaction_id&#39;: transaction_id,<br>            &#39;processor&#39;: self.name,<br>            &#39;masked_card&#39;: masked_card,<br>            &#39;amount&#39;: amount,<br>            &#39;message&#39;: f&#39;Payment of ${amount} processed successfully&#39;<br>        }<br><br>class PayPalProcessor(PaymentProcessor):<br>    &quot;&quot;&quot;PayPal payment implementation&quot;&quot;&quot;<br>    <br>    def __init__(self, api_key):<br>        super().__init__(&quot;PayPal&quot;)<br>        self.api_key = api_key<br>        self.api_endpoint = &quot;https://api.paypal.com/v2/payments&quot;<br>    <br>    def process_payment(self, amount, customer_info):<br>        self.validate_payment(amount)<br>        <br>        # PayPal specific processing<br>        email = customer_info.get(&#39;email&#39;, &#39;&#39;)<br>        <br>        # Generate PayPal transaction<br>        transaction_id = f&quot;PP-{self.generate_transaction_id()}&quot;<br>        <br>        # Simulate OAuth token exchange and API call<br>        import time<br>        time.sleep(0.3)<br>        <br>        # Log the transaction<br>        self.log_transaction(amount, &#39;SUCCESS&#39;, transaction_id)<br>        <br>        return {<br>            &#39;success&#39;: True,<br>            &#39;transaction_id&#39;: transaction_id,<br>            &#39;processor&#39;: self.name,<br>            &#39;paypal_email&#39;: email,<br>            &#39;amount&#39;: amount,<br>            &#39;message&#39;: f&#39;PayPal payment of ${amount} completed&#39;<br>        }<br><br>class CryptocurrencyProcessor(PaymentProcessor):<br>    &quot;&quot;&quot;Cryptocurrency payment implementation&quot;&quot;&quot;<br>    <br>    def __init__(self, blockchain_network):<br>        super().__init__(&quot;Cryptocurrency&quot;)<br>        self.blockchain_network = blockchain_network<br>        self.confirmation_blocks = 3<br>    <br>    def process_payment(self, amount, customer_info):<br>        self.validate_payment(amount)<br>        <br>        # Crypto specific processing<br>        wallet_address = customer_info.get(&#39;wallet_address&#39;, &#39;&#39;)<br>        crypto_type = customer_info.get(&#39;crypto_type&#39;, &#39;BTC&#39;)<br>        <br>        # Convert to crypto amount (simplified)<br>        exchange_rates = {&#39;BTC&#39;: 45000, &#39;ETH&#39;: 3000, &#39;USDT&#39;: 1}<br>        crypto_amount = amount / exchange_rates.get(crypto_type, 1)<br>        <br>        # Generate blockchain transaction<br>        transaction_id = f&quot;0x{self.generate_transaction_id()}&quot;<br>        <br>        # Simulate blockchain confirmation<br>        import time<br>        time.sleep(0.7)<br>        <br>        # Log the transaction<br>        self.log_transaction(amount, &#39;SUCCESS&#39;, transaction_id)<br>        <br>        return {<br>            &#39;success&#39;: True,<br>            &#39;transaction_id&#39;: transaction_id,<br>            &#39;processor&#39;: self.name,<br>            &#39;wallet&#39;: wallet_address[:8] + &#39;...&#39;,<br>            &#39;amount_usd&#39;: amount,<br>            &#39;amount_crypto&#39;: f&quot;{crypto_amount:.8f} {crypto_type}&quot;,<br>            &#39;confirmations&#39;: self.confirmation_blocks,<br>            &#39;message&#39;: f&#39;Crypto payment of {crypto_amount:.8f} {crypto_type} confirmed&#39;<br>        }<br><br>class BankTransferProcessor(PaymentProcessor):<br>    &quot;&quot;&quot;Bank transfer payment implementation&quot;&quot;&quot;<br>    <br>    def __init__(self, bank_code):<br>        super().__init__(&quot;Bank Transfer&quot;)<br>        self.bank_code = bank_code<br>        self.clearing_house = &quot;ACH&quot;<br>    <br>    def process_payment(self, amount, customer_info):<br>        self.validate_payment(amount)<br>        <br>        # Bank transfer specific processing<br>        account_number = customer_info.get(&#39;account_number&#39;, &#39;&#39;)<br>        routing_number = customer_info.get(&#39;routing_number&#39;, &#39;&#39;)<br>        <br>        # Generate ACH transaction<br>        transaction_id = f&quot;ACH-{self.generate_transaction_id()}&quot;<br>        <br>        # Simulate ACH processing<br>        import time<br>        time.sleep(0.4)<br>        <br>        # Log the transaction<br>        self.log_transaction(amount, &#39;SUCCESS&#39;, transaction_id)<br>        <br>        return {<br>            &#39;success&#39;: True,<br>            &#39;transaction_id&#39;: transaction_id,<br>            &#39;processor&#39;: self.name,<br>            &#39;account&#39;: f&quot;****{account_number[-4:]}&quot;,<br>            &#39;routing&#39;: routing_number,<br>            &#39;amount&#39;: amount,<br>            &#39;clearing&#39;: self.clearing_house,<br>            &#39;message&#39;: f&#39;Bank transfer of ${amount} initiated&#39;<br>        }</pre><h3>The Power of Polymorphic Functions</h3><p>Now, here’s where polymorphism truly shines. We can write a single function that works with ANY payment processor:</p><pre>def process_order(order_id, items, payment_processor: PaymentProcessor, customer_info):<br>    &quot;&quot;&quot;<br>    Process an order using any payment processor<br>    This function is polymorphic - it works with any PaymentProcessor implementation<br>    &quot;&quot;&quot;<br>    <br>    # Calculate order total<br>    total = sum(item[&#39;price&#39;] * item[&#39;quantity&#39;] for item in items)<br>    <br>    # Apply tax (simplified)<br>    tax_rate = 0.08<br>    tax = total * tax_rate<br>    final_amount = total + tax<br>    <br>    print(f&quot;Processing Order #{order_id}&quot;)<br>    print(f&quot;Subtotal: ${total:.2f}&quot;)<br>    print(f&quot;Tax: ${tax:.2f}&quot;)<br>    print(f&quot;Total: ${final_amount:.2f}&quot;)<br>    print(f&quot;Payment Method: {payment_processor.name}&quot;)<br>    <br>    try:<br>        # Process payment polymorphically<br>        # Same method call, different implementations<br>        result = payment_processor.process_payment(final_amount, customer_info)<br>        <br>        if result[&#39;success&#39;]:<br>            print(f&quot;✅ Payment successful!&quot;)<br>            print(f&quot;Transaction ID: {result[&#39;transaction_id&#39;]}&quot;)<br>            <br>            # Create order record<br>            order = {<br>                &#39;order_id&#39;: order_id,<br>                &#39;items&#39;: items,<br>                &#39;total&#39;: final_amount,<br>                &#39;payment_method&#39;: payment_processor.name,<br>                &#39;transaction_id&#39;: result[&#39;transaction_id&#39;],<br>                &#39;status&#39;: &#39;COMPLETED&#39;<br>            }<br>            return order<br>        <br>    except Exception as e:<br>        print(f&quot;❌ Payment failed: {e}&quot;)<br>        return None<br><br># Using the polymorphic system<br>processors = {<br>    &#39;credit_card&#39;: CreditCardProcessor(&#39;MERCHANT_123&#39;),<br>    &#39;paypal&#39;: PayPalProcessor(&#39;API_KEY_456&#39;),<br>    &#39;crypto&#39;: CryptocurrencyProcessor(&#39;ethereum&#39;),<br>    &#39;bank&#39;: BankTransferProcessor(&#39;BANK_789&#39;)<br>}<br># Same order, different payment methods<br>order_items = [<br>    {&#39;name&#39;: &#39;Laptop&#39;, &#39;price&#39;: 999.99, &#39;quantity&#39;: 1},<br>    {&#39;name&#39;: &#39;Mouse&#39;, &#39;price&#39;: 29.99, &#39;quantity&#39;: 2}<br>]<br># Process with different payment methods<br>customer_data = {<br>    &#39;credit_card&#39;: {&#39;card_number&#39;: &#39;1234567812345678&#39;, &#39;cvv&#39;: &#39;123&#39;},<br>    &#39;paypal&#39;: {&#39;email&#39;: &#39;customer@example.com&#39;},<br>    &#39;crypto&#39;: {&#39;wallet_address&#39;: &#39;1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa&#39;, &#39;crypto_type&#39;: &#39;BTC&#39;},<br>    &#39;bank&#39;: {&#39;account_number&#39;: &#39;9876543210&#39;, &#39;routing_number&#39;: &#39;123456789&#39;}<br>}<br>for payment_type, processor in processors.items():<br>    print(f&quot;\n{&#39;=&#39;*60}&quot;)<br>    order = process_order(<br>        order_id=f&quot;ORD-{random.randint(1000, 9999)}&quot;,<br>        items=order_items,<br>        payment_processor=processor,  # Polymorphic parameter<br>        customer_info=customer_data[payment_type]<br>    )</pre><h3>Method Overloading: The Python Way</h3><p>Traditional method overloading (multiple methods with the same name but different parameters) doesn’t exist in Python. However, Python offers elegant alternatives that achieve the same flexibility:</p><pre>class Calculator:<br>    &quot;&quot;&quot;Demonstrates Python&#39;s approach to method overloading&quot;&quot;&quot;<br>    <br>    # Approach 1: Default parameters<br>    def add(self, a, b=None, c=None):<br>        &quot;&quot;&quot;Overloaded add method using default parameters&quot;&quot;&quot;<br>        if b is None:<br>            return a  # Single number<br>        elif c is None:<br>            return a + b  # Two numbers<br>        else:<br>            return a + b + c  # Three numbers<br>    <br>    # Approach 2: Using *args<br>    def multiply(self, *args):<br>        &quot;&quot;&quot;Overloaded multiply using *args&quot;&quot;&quot;<br>        if len(args) == 0:<br>            return 0<br>        elif len(args) == 1:<br>            return args[0]<br>        else:<br>            result = 1<br>            for num in args:<br>                result *= num<br>            return result<br>    <br>    # Approach 3: Type checking<br>    def process(self, data):<br>        &quot;&quot;&quot;Different behavior based on input type&quot;&quot;&quot;<br>        if isinstance(data, str):<br>            return f&quot;Processing string: {data.upper()}&quot;<br>        elif isinstance(data, (int, float)):<br>            return f&quot;Processing number: {data * 2}&quot;<br>        elif isinstance(data, list):<br>            return f&quot;Processing list of {len(data)} items: {sum(data)}&quot;<br>        elif isinstance(data, dict):<br>            return f&quot;Processing dict with keys: {list(data.keys())}&quot;<br>        else:<br>            return f&quot;Unknown type: {type(data).__name__}&quot;<br>    <br>    # Approach 4: Using functools.singledispatch<br>    from functools import singledispatch<br>    <br>    @singledispatch<br>    @staticmethod<br>    def format_data(data):<br>        &quot;&quot;&quot;Generic format method - default implementation&quot;&quot;&quot;<br>        return f&quot;Generic: {str(data)}&quot;<br>    <br>    @format_data.register(str)<br>    @staticmethod<br>    def _(data):<br>        return f&quot;String: &#39;{data}&#39;&quot;<br>    <br>    @format_data.register(int)<br>    @staticmethod<br>    def _(data):<br>        return f&quot;Integer: {data:,}&quot;<br>    <br>    @format_data.register(float)<br>    @staticmethod<br>    def _(data):<br>        return f&quot;Float: {data:.2f}&quot;<br>    <br>    @format_data.register(list)<br>    @staticmethod<br>    def _(data):<br>        return f&quot;List: [{&#39;, &#39;.join(map(str, data))}]&quot;<br><br># Test method overloading<br>print(&quot;\n=== Method Overloading Demo ===&quot;)<br>calc = Calculator()<br><br># Test overloaded add<br>print(&quot;Add method overloading:&quot;)<br>print(f&quot;  add(5): {calc.add(5)}&quot;)<br>print(f&quot;  add(5, 3): {calc.add(5, 3)}&quot;)<br>print(f&quot;  add(5, 3, 2): {calc.add(5, 3, 2)}&quot;)<br><br># Test *args multiply<br>print(&quot;\nMultiply method overloading:&quot;)<br>print(f&quot;  multiply(): {calc.multiply()}&quot;)<br>print(f&quot;  multiply(5): {calc.multiply(5)}&quot;)<br>print(f&quot;  multiply(2, 3, 4): {calc.multiply(2, 3, 4)}&quot;)<br><br># Test type-based processing<br>print(&quot;\nType-based processing:&quot;)<br>test_data = [&quot;hello&quot;, 42, [1, 2, 3, 4, 5], {&quot;a&quot;: 1, &quot;b&quot;: 2}]<br>for data in test_data:<br>    print(f&quot;  {calc.process(data)}&quot;)<br><br># Test singledispatch<br>print(&quot;\nSingledispatch formatting:&quot;)<br>test_values = [&quot;Hello&quot;, 1234567, 3.14159, [1, 2, 3]]<br>for value in test_values:<br>    print(f&quot;  {Calculator.format_data(value)}&quot;)</pre><h3>Operator Polymorphism: Making Objects Pythonic</h3><p>Operator overloading allows your custom objects to work seamlessly with Python’s built-in operators, making them feel native to the language:</p><pre># Simple Operator Overloading Example<br><br>class Box:<br>    &quot;&quot;&quot;<br>    A simple Box class that demonstrates operator overloading.<br>    Imagine a box that can hold items.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, items):<br>        self.items = items<br>    <br>    def __str__(self):<br>        &quot;&quot;&quot;Define how print() displays our box&quot;&quot;&quot;<br>        return f&quot;Box({self.items} items)&quot;<br>    <br>    def __add__(self, other):<br>        &quot;&quot;&quot;Define what happens when we use + operator&quot;&quot;&quot;<br>        if isinstance(other, Box):<br>            # Adding two boxes combines their items<br>            return Box(self.items + other.items)<br>        elif isinstance(other, int):<br>            # Adding a number adds that many items<br>            return Box(self.items + other)<br>    <br>    def __eq__(self, other):<br>        &quot;&quot;&quot;Define what happens when we use == operator&quot;&quot;&quot;<br>        if isinstance(other, Box):<br>            return self.items == other.items<br>        return False<br>    <br>    def __lt__(self, other):<br>        &quot;&quot;&quot;Define what happens when we use &lt; operator&quot;&quot;&quot;<br>        if isinstance(other, Box):<br>            return self.items &lt; other.items<br>        return False<br>    <br>    def __len__(self):<br>        &quot;&quot;&quot;Define what happens when we use len() function&quot;&quot;&quot;<br>        return self.items<br><br># Using our Box class with operators<br>print(&quot;=== Simple Operator Overloading Demo ===\n&quot;)<br># Create boxes<br>box1 = Box(5)<br>box2 = Box(3)<br>box3 = Box(5)<br># Use + operator (calls __add__)<br>print(f&quot;box1: {box1}&quot;)<br>print(f&quot;box2: {box2}&quot;)<br>print(f&quot;box1 + box2 = {box1 + box2}&quot;)<br>print(f&quot;box1 + 10 = {box1 + 10}\n&quot;)<br># Use == operator (calls __eq__)<br>print(f&quot;box1 == box2: {box1 == box2}&quot;)<br>print(f&quot;box1 == box3: {box1 == box3}\n&quot;)<br># Use &lt; operator (calls __lt__)<br>print(f&quot;box2 &lt; box1: {box2 &lt; box1}&quot;)<br>print(f&quot;box1 &lt; box2: {box1 &lt; box2}\n&quot;)<br># Use len() function (calls __len__)<br>print(f&quot;len(box1): {len(box1)} items&quot;)<br>print(f&quot;len(box2): {len(box2)} items&quot;)<br><br>print(&quot;\n&quot; + &quot;=&quot;*50 + &quot;\n&quot;)<br><br>class Student:<br>    &quot;&quot;&quot;<br>    Another simple example: Student class with grades<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, name, grades):<br>        self.name = name<br>        self.grades = grades  # List of grades<br>    <br>    def __str__(self):<br>        avg = sum(self.grades) / len(self.grades) if self.grades else 0<br>        return f&quot;{self.name} (avg: {avg:.1f})&quot;<br>    <br>    def __add__(self, grade):<br>        &quot;&quot;&quot;Add a new grade using + operator&quot;&quot;&quot;<br>        if isinstance(grade, (int, float)):<br>            # Return new Student object with added grade<br>            new_grades = self.grades + [grade]<br>            return Student(self.name, new_grades)<br>    <br>    def __gt__(self, other):<br>        &quot;&quot;&quot;Compare students by average grade using &gt; operator&quot;&quot;&quot;<br>        if isinstance(other, Student):<br>            my_avg = sum(self.grades) / len(self.grades) if self.grades else 0<br>            other_avg = sum(other.grades) / len(other.grades) if other.grades else 0<br>            return my_avg &gt; other_avg<br>        return False<br>    <br>    def __len__(self):<br>        &quot;&quot;&quot;Return number of grades when using len()&quot;&quot;&quot;<br>        return len(self.grades)<br><br># Using Student class<br>print(&quot;=== Student Grade Example ===\n&quot;)<br># Create students<br>alice = Student(&quot;Alice&quot;, [85, 90, 88])<br>bob = Student(&quot;Bob&quot;, [78, 82, 80])<br>print(f&quot;Initial students:&quot;)<br>print(f&quot;  {alice}&quot;)<br>print(f&quot;  {bob}&quot;)<br># Add a grade using + operator<br>alice_updated = alice + 95<br>print(f&quot;\nAfter adding grade 95 to Alice:&quot;)<br>print(f&quot;  {alice_updated}&quot;)<br># Compare students using &gt; operator<br>print(f&quot;\nAlice &gt; Bob: {alice &gt; bob}&quot;)<br>print(f&quot;Bob &gt; Alice: {bob &gt; alice}&quot;)<br># Get number of grades using len()<br>print(f&quot;\nNumber of grades:&quot;)<br>print(f&quot;  Alice has {len(alice)} grades&quot;)<br>print(f&quot;  Bob has {len(bob)} grades&quot;)<br><br>print(&quot;\n&quot; + &quot;=&quot;*50 + &quot;\n&quot;)<br><br># Most Common Operator Methods<br>print(&quot;=== Common Operator Methods Reference ===\n&quot;)<br>print(&quot;Arithmetic Operators:&quot;)<br>print(&quot;  __add__(self, other)      →  self + other&quot;)<br>print(&quot;  __sub__(self, other)      →  self - other&quot;)<br>print(&quot;  __mul__(self, other)      →  self * other&quot;)<br>print(&quot;  __truediv__(self, other)  →  self / other&quot;)<br>print(&quot;  __mod__(self, other)      →  self % other&quot;)<br>print(&quot;  __pow__(self, other)      →  self ** other&quot;)<br>print(&quot;\nComparison Operators:&quot;)<br>print(&quot;  __eq__(self, other)       →  self == other&quot;)<br>print(&quot;  __ne__(self, other)       →  self != other&quot;)<br>print(&quot;  __lt__(self, other)       →  self &lt; other&quot;)<br>print(&quot;  __le__(self, other)       →  self &lt;= other&quot;)<br>print(&quot;  __gt__(self, other)       →  self &gt; other&quot;)<br>print(&quot;  __ge__(self, other)       →  self &gt;= other&quot;)<br>print(&quot;\nOther Useful Methods:&quot;)<br>print(&quot;  __str__(self)             →  str(self) or print(self)&quot;)<br>print(&quot;  __len__(self)             →  len(self)&quot;)<br>print(&quot;  __getitem__(self, key)    →  self[key]&quot;)<br>print(&quot;  __setitem__(self, key, v) →  self[key] = v&quot;)<br>print(&quot;  __contains__(self, item)  →  item in self&quot;)<br>print(&quot;  __bool__(self)            →  bool(self)&quot;)<br><br>print(&quot;\n&quot; + &quot;=&quot;*50 + &quot;\n&quot;)<br><br>class ShoppingCart:<br>    &quot;&quot;&quot;<br>    Practical example: Shopping cart with operator overloading<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self):<br>        self.items = []<br>    <br>    def __add__(self, item):<br>        &quot;&quot;&quot;Add item to cart using + operator&quot;&quot;&quot;<br>        self.items.append(item)<br>        return self<br>    <br>    def __sub__(self, item_name):<br>        &quot;&quot;&quot;Remove item from cart using - operator&quot;&quot;&quot;<br>        self.items = [item for item in self.items if item[&#39;name&#39;] != item_name]<br>        return self<br>    <br>    def __len__(self):<br>        &quot;&quot;&quot;Get number of items using len()&quot;&quot;&quot;<br>        return len(self.items)<br>    <br>    def __getitem__(self, index):<br>        &quot;&quot;&quot;Get item by index using cart[index]&quot;&quot;&quot;<br>        return self.items[index]<br>    <br>    def __contains__(self, item_name):<br>        &quot;&quot;&quot;Check if item in cart using &#39;in&#39; operator&quot;&quot;&quot;<br>        return any(item[&#39;name&#39;] == item_name for item in self.items)<br>    <br>    def __str__(self):<br>        &quot;&quot;&quot;String representation&quot;&quot;&quot;<br>        if not self.items:<br>            return &quot;Empty Cart&quot;<br>        total = sum(item[&#39;price&#39;] for item in self.items)<br>        return f&quot;Cart: {len(self.items)} items, Total: ${total:.2f}&quot;<br><br>print(&quot;=== Shopping Cart Example ===\n&quot;)<br># Create cart<br>cart = ShoppingCart()<br># Add items using + operator<br>cart = cart + {&#39;name&#39;: &#39;Apple&#39;, &#39;price&#39;: 1.99}<br>cart = cart + {&#39;name&#39;: &#39;Bread&#39;, &#39;price&#39;: 2.49}<br>cart = cart + {&#39;name&#39;: &#39;Milk&#39;, &#39;price&#39;: 3.99}<br>print(f&quot;After adding items: {cart}&quot;)<br># Check if item exists using &#39;in&#39; operator<br>print(f&quot;\n&#39;Bread&#39; in cart: {&#39;Bread&#39; in cart}&quot;)<br>print(f&quot;&#39;Eggs&#39; in cart: {&#39;Eggs&#39; in cart}&quot;)<br># Get item by index using [] operator<br>print(f&quot;\nFirst item: {cart[0]}&quot;)<br>print(f&quot;Last item: {cart[-1]}&quot;)<br># Remove item using - operator<br>cart = cart - &#39;Bread&#39;<br>print(f&quot;\nAfter removing Bread: {cart}&quot;)<br># Get number of items using len()<br>print(f&quot;Number of items: {len(cart)}&quot;)</pre><h3>Best Practices for Polymorphism</h3><h3>1. Design Clear Interfaces</h3><p>Always define clear, minimal interfaces that capture the essential behavior:</p><pre>from abc import ABC, abstractmethod<br><br>class StorageInterface(ABC):<br>    &quot;&quot;&quot;Clear, minimal interface for storage systems&quot;&quot;&quot;<br>    <br>    @abstractmethod<br>    def save(self, key: str, data: any) -&gt; bool:<br>        &quot;&quot;&quot;Save data with given key&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def load(self, key: str) -&gt; any:<br>        &quot;&quot;&quot;Load data by key&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def delete(self, key: str) -&gt; bool:<br>        &quot;&quot;&quot;Delete data by key&quot;&quot;&quot;<br>        pass<br>    <br>    @abstractmethod<br>    def exists(self, key: str) -&gt; bool:<br>        &quot;&quot;&quot;Check if key exists&quot;&quot;&quot;<br>        pass</pre><h3>2. Follow the Liskov Substitution Principle</h3><p>Derived classes should be substitutable for their base classes without breaking the program:</p><pre>class Bird(ABC):<br>    @abstractmethod<br>    def move(self):<br>        pass<br><br>class FlyingBird(Bird):<br>    def move(self):<br>        return &quot;Flying through the air&quot;<br><br>class SwimmingBird(Bird):<br>    def move(self):<br>        return &quot;Swimming in water&quot;<br><br># Good: Both can substitute for Bird<br>sparrow = FlyingBird()<br>penguin = SwimmingBird()<br>birds = [sparrow, penguin]<br><br>for bird in birds:<br>    print(bird.move())  # Works for both</pre><h3>3. Use Type Hints for Better Documentation</h3><pre>from typing import Protocol, List, Dict, Any<br><br>class PaymentProtocol(Protocol):<br>    &quot;&quot;&quot;Protocol defining payment interface&quot;&quot;&quot;<br>    <br>    def process_payment(self, amount: float, customer_info: Dict[str, Any]) -&gt; Dict[str, Any]:<br>        ...<br>    <br>    def validate_payment(self, amount: float) -&gt; bool:<br>        ...<br>def handle_payments(processors: List[PaymentProtocol], amount: float) -&gt; None:<br>    &quot;&quot;&quot;Type-hinted polymorphic function&quot;&quot;&quot;<br>    for processor in processors:<br>        if processor.validate_payment(amount):<br>            result = processor.process_payment(amount, {})<br>            print(f&quot;Processed: {result}&quot;)</pre><h3>4. Avoid Deep Inheritance Hierarchies</h3><p>Prefer composition over deep inheritance:</p><pre># Prefer this (composition)<br>class EmailNotifier:<br>    def send(self, message):<br>        print(f&quot;Email: {message}&quot;)<br><br>class SMSNotifier:<br>    def send(self, message):<br>        print(f&quot;SMS: {message}&quot;)<br>class NotificationService:<br>    def __init__(self, notifiers):<br>        self.notifiers = notifiers<br>    <br>    def notify_all(self, message):<br>        for notifier in self.notifiers:<br>            notifier.send(message)<br># Over deep inheritance<br>service = NotificationService([EmailNotifier(), SMSNotifier()])<br>service.notify_all(&quot;System update completed&quot;)</pre><h3>Performance Consideration</h3><p>Polymorphism in Python has minimal performance overhead:</p><pre>import timeit<br><br>class DirectCalculator:<br>    def calculate(self, a, b):<br>        return a + b<br>class PolymorphicCalculator:<br>    def calculate(self, a, b):<br>        return self._add(a, b)<br>    <br>    def _add(self, a, b):<br>        return a + b<br># Performance comparison<br>direct = DirectCalculator()<br>polymorphic = PolymorphicCalculator()<br>direct_time = timeit.timeit(lambda: direct.calculate(5, 3), number=1000000)<br>poly_time = timeit.timeit(lambda: polymorphic.calculate(5, 3), number=1000000)<br>print(f&quot;Direct call: {direct_time:.4f} seconds&quot;)<br>print(f&quot;Polymorphic call: {poly_time:.4f} seconds&quot;)<br>print(f&quot;Overhead: {((poly_time - direct_time) / direct_time * 100):.2f}%&quot;)</pre><h3>Common Pitfalls and How to Avoid Them</h3><h3>1. Violating the Interface Contract</h3><pre># Bad: Breaks the contract<br>class BadProcessor(PaymentProcessor):<br>    def process_payment(self, amount, customer_info):<br>        # Returns string instead of dict - breaks contract!<br>        return &quot;Payment processed&quot;<br><br># Good: Maintains the contract<br>class GoodProcessor(PaymentProcessor):<br>    def process_payment(self, amount, customer_info):<br>        # Returns expected dict structure<br>        return {<br>            &#39;success&#39;: True,<br>            &#39;transaction_id&#39;: &#39;TXN123&#39;,<br>            &#39;amount&#39;: amount<br>        }</pre><h3>2. Overusing Inheritance</h3><pre># Bad: Unnecessary inheritance<br>class Animal:<br>    pass<br><br>class Dog(Animal):<br>    pass<br>class Poodle(Dog):<br>    pass<br>class ToyPoodle(Poodle):<br>    pass<br># Good: Use composition<br>class Dog:<br>    def __init__(self, breed, size):<br>        self.breed = breed<br>        self.size = size<br>poodle = Dog(breed=&quot;Poodle&quot;, size=&quot;Standard&quot;)<br>toy_poodle = Dog(breed=&quot;Poodle&quot;, size=&quot;Toy&quot;)</pre><h3>Conclusion</h3><p>Polymorphism is more than just a programming concept — it’s a powerful design principle that enables you to write flexible, maintainable, and extensible code. By allowing objects of different types to be treated uniformly through common interfaces, polymorphism reduces code duplication, improves modularity, and makes your applications easier to extend and maintain.</p><p>Key takeaways:</p><ol><li><strong>Runtime polymorphism</strong> through method overriding provides the foundation for flexible design patterns</li><li><strong>Method overloading</strong> in Python can be achieved through default parameters, *args/**kwargs, and single dispatch</li><li><strong>Operator overloading</strong> makes your custom objects feel native to Python</li><li><strong>Clear interfaces</strong> and proper abstraction are crucial for effective polymorphism</li><li><strong>Composition</strong> often provides better flexibility than deep inheritance hierarchies</li></ol><p>As you continue your Python journey, remember that polymorphism isn’t just about writing clever code — it’s about creating systems that can grow and adapt to changing requirements without requiring major rewrites. Master polymorphism, and you’ll find yourself writing code that’s not just functional, but elegant and future-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd07e3485b6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/mastering-polymorphism-in-python-one-interface-many-implementations-bd07e3485b6e">Mastering Polymorphism in Python: One Interface, Many Implementations</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Inheritance & MRO: The Complete Guide]]></title>
            <link>https://medium.com/codex/python-inheritance-mro-the-complete-guide-934337ff58d4?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/934337ff58d4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 19:24:22 GMT</pubDate>
            <atom:updated>2025-09-05T12:25:51.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*8f4CRJwQmXTc9BlMduRUKQ.png" /></figure><h3>What is Inheritance?</h3><p>Think of inheritance like family traits. Just like you inherit your parents’ features (eye color, height), Python classes can inherit attributes and methods from other classes.</p><p><strong>Real-world analogy:</strong></p><ul><li>Your <strong>parent</strong> gives you basic human traits (breathing, eating, sleeping)</li><li>You <strong>inherit</strong> these traits automatically</li><li>You can <strong>add</strong> your own unique traits (your personality, skills)</li><li>You can <strong>modify</strong> inherited traits (maybe you eat differently than your parents)</li></ul><h3>Creating a Parent Class</h3><pre># This is our &quot;parent&quot; class - the base class<br>class Vehicle:<br>    def __init__(self, brand, model, year):<br>        self.brand = brand<br>        self.model = model  <br>        self.year = year<br>        self.is_running = False<br>        <br>    def start(self):<br>        self.is_running = True<br>        return f&quot;{self.brand} {self.model} started&quot;<br>    <br>    def stop(self):<br>        self.is_running = False<br>        return f&quot;{self.brand} {self.model} stopped&quot;<br>    <br>    def get_info(self):<br>        return f&quot;{self.year} {self.brand} {self.model}&quot;<br>    <br>    def __str__(self):<br>        return f&quot;{self.brand} {self.model}&quot;<br><br># Test the parent class<br>print(&quot;=== Testing Parent Class ===&quot;)<br>vehicle = Vehicle(&quot;Toyota&quot;, &quot;Generic&quot;, 2020)<br>print(vehicle.get_info())  # 2020 Toyota Generic<br>print(vehicle.start())     # Toyota Generic started<br>print(vehicle.stop())      # Toyota Generic stopped</pre><h3>Creating a Child Class (Single Inheritance)</h3><pre># This is our &quot;child&quot; class - inherits from Vehicle<br>class Car(Vehicle):  # Car inherits everything from Vehicle<br>    pass  # For now, just inherit everything as-is</pre><pre># Test inheritance<br>print(&quot;\n=== Testing Basic Inheritance ===&quot;)<br>car = Car(&quot;Honda&quot;, &quot;Civic&quot;, 2023)</pre><pre># Car automatically has all Vehicle methods!<br>print(car.get_info())  # 2023 Honda Civic (inherited method)<br>print(car.start())     # Honda Civic started (inherited method)<br>print(car.brand)       # Honda (inherited attribute)<br>print(car.is_running)  # True (inherited attribute)</pre><h3>The Flow: How Inheritance Works</h3><pre># When you write this:<br>car = Car(&quot;Honda&quot;, &quot;Civic&quot;, 2023)<br><br># Python does this automatically:<br># 1. &quot;Creating Car instance&quot;<br># 2. &quot;Car doesn&#39;t have __init__, let me check parent Vehicle&quot;<br># 3. &quot;Found Vehicle.__init__, using that&quot;<br># 4. &quot;Calling Vehicle.__init__(car, &#39;Honda&#39;, &#39;Civic&#39;, 2023)&quot;<br># 5. &quot;Car instance created with Vehicle&#39;s attributes&quot;<br># When you write this:<br>car.start()<br># Python does this automatically:<br># 1. &quot;Looking for start() method in Car class&quot;<br># 2. &quot;Not found in Car, checking parent Vehicle&quot;<br># 3. &quot;Found Vehicle.start(), calling it&quot;<br># 4. &quot;Method executes with car as self&quot;</pre><h3>Adding Child-Specific Features</h3><pre>class Car(Vehicle):<br>    def __init__(self, brand, model, year, doors, fuel_type):<br>        # Call parent constructor first<br>        super().__init__(brand, model, year)<br>        # Add car-specific attributes<br>        self.doors = doors<br>        self.fuel_type = fuel_type<br>        self.fuel_level = 100<br>    <br>    def honk(self):  # New method specific to cars<br>        return f&quot;{self.brand} {self.model} goes BEEP BEEP!&quot;<br>    <br>    def drive(self, distance):  # New method<br>        if not self.is_running:<br>            return f&quot;Cannot drive - {self.brand} {self.model} is not running&quot;<br>        <br>        fuel_used = distance * 0.1  # Simple fuel calculation<br>        if fuel_used &gt; self.fuel_level:<br>            return f&quot;Not enough fuel! Need {fuel_used}, have {self.fuel_level}&quot;<br>        <br>        self.fuel_level -= fuel_used<br>        return f&quot;Drove {distance} miles. Fuel remaining: {self.fuel_level}%&quot;<br>    <br>    def refuel(self):<br>        self.fuel_level = 100<br>        return f&quot;{self.brand} {self.model} refueled to 100%&quot;<br><br># Test child class with new features<br>print(&quot;\n=== Testing Enhanced Child Class ===&quot;)<br>car = Car(&quot;Tesla&quot;, &quot;Model 3&quot;, 2024, 4, &quot;Electric&quot;)<br># Inherited methods still work<br>print(car.get_info())     # 2024 Tesla Model 3 (inherited)<br>print(car.start())        # Tesla Model 3 started (inherited)<br># New methods work too<br>print(car.honk())         # Tesla Model 3 goes BEEP BEEP! (new)<br>print(car.drive(50))      # Drove 50 miles... (new)<br>print(car.drive(1000))    # Not enough fuel... (new)<br>print(car.refuel())       # Tesla Model 3 refueled... (new)</pre><h3>The Flow: How super() Works</h3><pre># When you write this in Car.__init__:<br>super().__init__(brand, model, year)<br><br># Python does this automatically:<br># 1. &quot;I see super().__init__ call from Car class&quot;<br># 2. &quot;Super refers to the parent class of Car&quot;<br># 3. &quot;Parent of Car is Vehicle&quot;<br># 4. &quot;Call Vehicle.__init__(self, brand, model, year)&quot;<br># 5. &quot;Vehicle.__init__ sets up brand, model, year, is_running&quot;<br># 6. &quot;Return to Car.__init__ to set up doors, fuel_type, fuel_level&quot;</pre><h3>Method Overriding</h3><pre>class Car(Vehicle):<br>    def __init__(self, brand, model, year, doors, fuel_type):<br>        super().__init__(brand, model, year)<br>        self.doors = doors<br>        self.fuel_type = fuel_type<br>        self.fuel_level = 100<br>    <br>    # Override parent&#39;s start method<br>    def start(self):<br>        if self.fuel_level &lt;= 0:<br>            return f&quot;Cannot start {self.brand} {self.model} - no fuel!&quot;<br>        <br>        self.is_running = True<br>        return f&quot;{self.brand} {self.model} engine started! Fuel: {self.fuel_level}%&quot;<br>    <br>    # Override parent&#39;s get_info method  <br>    def get_info(self):<br>        parent_info = super().get_info()  # Get parent&#39;s version first<br>        return f&quot;{parent_info}, {self.doors} doors, {self.fuel_type} fuel&quot;<br>    <br>    def honk(self):<br>        return f&quot;{self.brand} {self.model} goes BEEP BEEP!&quot;<br><br><br># Test method overriding<br>print(&quot;\n=== Testing Method Overriding ===&quot;)<br>car = Car(&quot;BMW&quot;, &quot;X5&quot;, 2023, 4, &quot;Gasoline&quot;)<br># Overridden methods use Car&#39;s version<br>print(car.start())        # BMW X5 engine started! (Car&#39;s version)<br>print(car.get_info())     # Enhanced info with doors and fuel (Car&#39;s version)<br># Create a regular vehicle to see the difference<br>vehicle = Vehicle(&quot;Ford&quot;, &quot;Transit&quot;, 2022)<br>print(vehicle.start())    # Ford Transit started (Vehicle&#39;s version)<br>print(vehicle.get_info()) # 2022 Ford Transit (Vehicle&#39;s version)</pre><h3>The Flow: Method Overriding</h3><pre># When you write this:<br>car.start()<br><br># Python does this automatically:<br># 1. &quot;Looking for start() method in Car class&quot;<br># 2. &quot;Found Car.start() method!&quot;<br># 3. &quot;Use Car&#39;s version, not Vehicle&#39;s version&quot;<br># 4. &quot;Call Car.start(car)&quot;<br># When you write this inside Car.start():<br>super().get_info()<br># Python does this automatically:<br># 1. &quot;I see super().get_info() call from Car class&quot;<br># 2. &quot;Super refers to Vehicle class&quot;<br># 3. &quot;Call Vehicle.get_info(self)&quot;<br># 4. &quot;Return Vehicle&#39;s result to Car method&quot;</pre><h3>Creating Multiple Child Classes</h3><pre>class Motorcycle(Vehicle):<br>    def __init__(self, brand, model, year, engine_size):<br>        super().__init__(brand, model, year)<br>        self.engine_size = engine_size<br>        self.has_sidecar = False<br>    <br>    def wheelie(self):<br>        if not self.is_running:<br>            return f&quot;Cannot do wheelie - {self.brand} {self.model} is not running&quot;<br>        return f&quot;{self.brand} {self.model} does an awesome wheelie! 🏍️&quot;<br>    <br>    def add_sidecar(self):<br>        self.has_sidecar = True<br>        return f&quot;Added sidecar to {self.brand} {self.model}&quot;<br>    <br>    def start(self):  # Override start method<br>        self.is_running = True<br>        return f&quot;{self.brand} {self.model} roars to life! VROOOOM!&quot;<br><br><br>class Truck(Vehicle):<br>    def __init__(self, brand, model, year, cargo_capacity):<br>        super().__init__(brand, model, year)<br>        self.cargo_capacity = cargo_capacity<br>        self.cargo_weight = 0<br>    <br>    def load_cargo(self, weight):<br>        if self.cargo_weight + weight &gt; self.cargo_capacity:<br>            return f&quot;Cannot load {weight}lbs - would exceed capacity of {self.cargo_capacity}lbs&quot;<br>        <br>        self.cargo_weight += weight<br>        return f&quot;Loaded {weight}lbs. Total cargo: {self.cargo_weight}/{self.cargo_capacity}lbs&quot;<br>    <br>    def start(self):  # Override start method<br>        if self.cargo_weight &gt; self.cargo_capacity * 0.9:  # 90% capacity<br>            return f&quot;{self.brand} {self.model} struggles to start with heavy load...&quot;<br>        <br>        self.is_running = True<br>        return f&quot;{self.brand} {self.model} diesel engine started with a rumble!&quot;<br><br><br># Test multiple child classes<br>print(&quot;\n=== Testing Multiple Child Classes ===&quot;)<br># Test Car<br>car = Car(&quot;Audi&quot;, &quot;A4&quot;, 2023, 4, &quot;Gasoline&quot;)<br>print(car.start())        # Audi A4 engine started!<br>print(car.honk())         # Audi A4 goes BEEP BEEP!<br># Test Motorcycle  <br>bike = Motorcycle(&quot;Harley&quot;, &quot;Davidson&quot;, 2022, 1200)<br>print(bike.start())       # Harley Davidson roars to life!<br>print(bike.wheelie())     # Harley Davidson does an awesome wheelie!<br># Test Truck<br>truck = Truck(&quot;Ford&quot;, &quot;F-150&quot;, 2024, 2000)<br>print(truck.start())      # Ford F-150 diesel engine started!<br>print(truck.load_cargo(500))  # Loaded 500lbs...<br>print(truck.load_cargo(1600)) # Loaded 1600lbs... (heavy load)<br>print(truck.stop())       # Ford F-150 stopped (inherited method)<br>print(truck.start())      # Ford F-150 struggles to start... (overridden with logic)</pre><h3>Understanding the Class Hierarchy</h3><pre># Let&#39;s visualize our inheritance tree<br>print(&quot;\n=== Class Hierarchy ===&quot;)<br>print(&quot;Vehicle (Parent)&quot;)<br>print(&quot;├── Car (Child)&quot;)<br>print(&quot;├── Motorcycle (Child)&quot;)  <br>print(&quot;└── Truck (Child)&quot;)<br><br>print(&quot;\n=== Method Resolution ===&quot;)<br>vehicles = [<br>    Car(&quot;Honda&quot;, &quot;Accord&quot;, 2023, 4, &quot;Hybrid&quot;),<br>    Motorcycle(&quot;Yamaha&quot;, &quot;R1&quot;, 2022, 1000),<br>    Truck(&quot;Chevy&quot;, &quot;Silverado&quot;, 2024, 3000)<br>]<br>for vehicle in vehicles:<br>    print(f&quot;\n{vehicle.__class__.__name__}:&quot;)<br>    print(f&quot;  Info: {vehicle.get_info()}&quot;)      # Car overrides, others inherit<br>    print(f&quot;  Start: {vehicle.start()}&quot;)        # All override differently<br>    print(f&quot;  Type: {type(vehicle).__name__}&quot;)  # Shows actual class<br>    print(f&quot;  Is Vehicle: {isinstance(vehicle, Vehicle)}&quot;)  # All are True!</pre><h3>Key Concepts Summary</h3><h3>1. Inheritance Basics</h3><pre>class Child(Parent):  # Child inherits from Parent<br>    pass              # Child gets all Parent methods and attributes</pre><h3>2. Constructor Inheritance</h3><pre>class Child(Parent):<br>    def __init__(self, child_arg, parent_arg):<br>        super().__init__(parent_arg)  # Call parent constructor<br>        self.child_arg = child_arg    # Add child-specific attributes</pre><h3>3. Method Overriding</h3><pre>class Child(Parent):<br>    def parent_method(self):          # Override parent&#39;s method<br>        parent_result = super().parent_method()  # Optionally use parent&#39;s version<br>        return f&quot;Child version: {parent_result}&quot;</pre><h3>4. The isinstance() and type() Functions</h3><pre>car = Car(&quot;Honda&quot;, &quot;Civic&quot;, 2023, 4, &quot;Gas&quot;)<br><br>print(isinstance(car, Car))      # True - car is a Car<br>print(isinstance(car, Vehicle))  # True - car is also a Vehicle<br>print(type(car).__name__)        # &quot;Car&quot; - actual class name</pre><h3>Multiple Inheritance — Step by Step</h3><h3>The Problem Single Inheritance Can’t Solve</h3><p>Imagine you want to create a <strong>Duck</strong>:</p><ul><li>A duck <strong>IS-A</strong> Animal (needs name, species, eat, sleep)</li><li>A duck <strong>CAN</strong> fly (needs altitude, fly method)</li><li>A duck <strong>CAN</strong> swim (needs depth, swim method)</li><li>A duck <strong>CAN</strong> walk (needs steps, walk method)</li></ul><p>With single inheritance, you’d have to put ALL these capabilities in one giant class. That’s messy and not reusable.</p><h3>Solution: Multiple Inheritance</h3><p>Instead, let’s create <strong>separate capability classes</strong> and combine them!</p><h3>Creating Capability Classes (Mixins)</h3><pre># Each class represents ONE capability<br>class Flyable:<br>    def __init__(self):<br>        self.can_fly = True<br>        self.altitude = 0<br>        print(&quot;Flyable.__init__ called&quot;)<br>    <br>    def fly(self):<br>        if not self.can_fly:<br>            return f&quot;Cannot fly!&quot;<br>        <br>        self.altitude += 100<br>        return f&quot;Flying at {self.altitude} feet&quot;<br>    <br>    def land(self):<br>        self.altitude = 0<br>        return &quot;Landed safely&quot;<br><br>class Swimmable:<br>    def __init__(self):<br>        self.can_swim = True<br>        self.depth = 0<br>        print(&quot;Swimmable.__init__ called&quot;)<br>    <br>    def swim(self):<br>        if not self.can_swim:<br>            return &quot;Cannot swim!&quot;<br>        <br>        self.depth += 10<br>        return f&quot;Swimming at {self.depth} feet deep&quot;<br>    <br>    def surface(self):<br>        self.depth = 0<br>        return &quot;Surfaced&quot;<br>class Walkable:<br>    def __init__(self):<br>        self.can_walk = True<br>        self.steps = 0<br>        print(&quot;Walkable.__init__ called&quot;)<br>    <br>    def walk(self):<br>        if not self.can_walk:<br>            return &quot;Cannot walk!&quot;<br>        <br>        self.steps += 10<br>        return f&quot;Walking... {self.steps} steps taken&quot;<br># Our base Animal class<br>class Animal:<br>    def __init__(self, name, species):<br>        self.name = name<br>        self.species = species<br>        self.energy = 100<br>        print(f&quot;Animal.__init__ called for {name}&quot;)<br>    <br>    def eat(self, food):<br>        self.energy = min(100, self.energy + 10)<br>        return f&quot;{self.name} eats {food} (Energy: {self.energy})&quot;<br>    <br>    def make_sound(self):<br>        return &quot;Some generic sound&quot;<br>    <br>    def __str__(self):<br>        return f&quot;{self.name} the {self.species}&quot;</pre><h3>Multiple Inheritance — The Magic Happens</h3><pre># Duck inherits from ALL four classes!<br>class Duck(Animal, Flyable, Swimmable, Walkable):<br>    def __init__(self, name):<br>        # Problem: We have 4 different __init__ methods!<br>        # Solution: Call each one manually (for now)<br>        Animal.__init__(self, name, &quot;Duck&quot;)<br>        Flyable.__init__(self)<br>        Swimmable.__init__(self)<br>        Walkable.__init__(self)<br>        print(&quot;Duck.__init__ called&quot;)<br>    <br>    def make_sound(self):<br>        return &quot;Quack! Quack!&quot;<br>    <br>    def migrate(self, destination):<br>        # Use inherited fly method<br>        fly_result = self.fly()<br>        return f&quot;{self.name} migrates to {destination}. {fly_result}&quot;<br><br># Let&#39;s test it!<br>print(&quot;=== Creating a Duck ===&quot;)<br>duck = Duck(&quot;Donald&quot;)<br>print(&quot;\n=== Testing Duck&#39;s Capabilities ===&quot;)<br>print(duck)                    # Donald the Duck (from Animal)<br>print(duck.make_sound())       # Quack! Quack! (Duck&#39;s override)<br>print(duck.eat(&quot;bread&quot;))       # Donald eats bread (from Animal)<br>print(duck.fly())              # Flying at 100 feet (from Flyable)<br>print(duck.swim())             # Swimming at 10 feet deep (from Swimmable)  <br>print(duck.walk())             # Walking... 10 steps taken (from Walkable)<br>print(duck.migrate(&quot;South&quot;))   # Donald migrates to South (Duck&#39;s method using fly)</pre><h3>Understanding Method Resolution Order (MRO)</h3><p>When Duck inherits from multiple classes, how does Python know which method to call when there are conflicts?</p><pre># Let&#39;s check Duck&#39;s MRO (Method Resolution Order)<br>print(&quot;\n=== Duck&#39;s MRO ===&quot;)<br>print(&quot;Duck.mro():&quot;, Duck.mro())<br><br># More readable version:<br>print(&quot;\nDuck&#39;s Method Resolution Order:&quot;)<br>for i, cls in enumerate(Duck.mro()):<br>    print(f&quot;{i + 1}. {cls.__name__}&quot;)<br># Output will be something like:<br># 1. Duck<br># 2. Animal  <br># 3. Flyable<br># 4. Swimmable<br># 5. Walkable<br># 6. object</pre><h3>The Flow: How MRO Works</h3><pre># When you write this:<br>duck.some_method()<br><br><br># Python does this automatically:<br># 1. &quot;I see some_method() call on Duck instance&quot;<br># 2. &quot;Let me check Duck.mro(): [Duck, Animal, Flyable, Swimmable, Walkable, object]&quot;<br># 3. &quot;First, check Duck class for some_method()&quot;<br># 4. &quot;If not found, check Animal class for some_method()&quot;<br># 5. &quot;If not found, check Flyable class for some_method()&quot;<br># 6. &quot;Continue through MRO until method found or AttributeError&quot;<br># 7. &quot;Call the FIRST method found in MRO order&quot;<br></pre><h3>Method Conflicts and Resolution</h3><p>What happens when multiple parent classes have the same method name?</p><pre># Let&#39;s create classes with conflicting method names<br>class Engine:<br>    def __init__(self):<br>        self.engine_running = False<br>        print(&quot;Engine.__init__ called&quot;)<br>    <br>    def start(self):<br>        self.engine_running = True<br>        return &quot;Engine started&quot;<br>    <br>    def status(self):<br>        return f&quot;Engine: {&#39;Running&#39; if self.engine_running else &#39;Off&#39;}&quot;<br><br><br>class Radio:<br>    def __init__(self):<br>        self.radio_on = False<br>        self.station = 101.5<br>        print(&quot;Radio.__init__ called&quot;)<br>    <br>    def start(self):  # Same method name as Engine!<br>        self.radio_on = True<br>        return f&quot;Radio tuned to {self.station} FM&quot;<br>    <br>    def status(self):  # Same method name as Engine!<br>        return f&quot;Radio: {&#39;On&#39; if self.radio_on else &#39;Off&#39;} - {self.station} FM&quot;<br><br>class Car(Engine, Radio):  # Inherits from both!<br>    def __init__(self, brand):<br>        self.brand = brand<br>        Engine.__init__(self)<br>        Radio.__init__(self)<br>        print(&quot;Car.__init__ called&quot;)<br><br><br># Test method resolution<br>print(&quot;\n=== Method Conflict Resolution ===&quot;)<br>print(&quot;Car MRO:&quot;, [cls.__name__ for cls in Car.mro()])<br># [Car, Engine, Radio, object]<br>car = Car(&quot;Toyota&quot;)<br>print(&quot;\nCalling car.start():&quot;)<br>result = car.start()  # Which start() method gets called?<br>print(result)         # &quot;Engine started&quot; - Engine comes first in MRO!<br>print(&quot;\nCalling car.status():&quot;)<br>result = car.status() # Which status() method gets called?<br>print(result)         # &quot;Engine: Running&quot; - Engine comes first in MRO!<br><br></pre><h3>The Flow: Method Conflict Resolution</h3><pre># When you write this:<br>car.start()<br><br># Python does this automatically:<br># 1. &quot;Looking for start() in Car.mro(): [Car, Engine, Radio, object]&quot;<br># 2. &quot;Not found in Car class&quot;<br># 3. &quot;Found in Engine class - STOP HERE!&quot;<br># 4. &quot;Call Engine.start(car)&quot;<br># 5. &quot;Radio.start() is ignored because Engine.start() was found first&quot;</pre><h3>Accessing “Shadowed” Methods</h3><p>What if you want to access Radio’s start method even though Engine’s comes first?</p><pre>class Car(Engine, Radio):<br>    def __init__(self, brand):<br>        self.brand = brand<br>        Engine.__init__(self)<br>        Radio.__init__(self)<br>        print(&quot;Car.__init__ called&quot;)<br>    <br>    def start_engine(self):<br>        # Explicitly call Engine&#39;s start<br>        return Engine.start(self)<br>    <br>    def start_radio(self):<br>        # Explicitly call Radio&#39;s start<br>        return Radio.start(self)<br>    <br>    def start_all(self):<br>        # Start both engine and radio<br>        engine_result = self.start_engine()<br>        radio_result = self.start_radio()<br>        return f&quot;{engine_result} and {radio_result}&quot;<br><br># Test explicit method calls<br>print(&quot;\n=== Accessing Shadowed Methods ===&quot;)<br>car = Car(&quot;Honda&quot;)<br>print(car.start_all())  # Engine started and Radio tuned to 101.5 FM<br># Check status of both<br>print(f&quot;Engine status: {Engine.status(car)}&quot;)<br>print(f&quot;Radio status: {Radio.status(car)}&quot;)</pre><h3>The Diamond Problem Preview</h3><p>What happens when multiple parent classes inherit from the same grandparent?</p><pre>class Animal:<br>    def __init__(self, name):<br>        self.name = name<br>        print(f&quot;Animal.__init__ for {name}&quot;)<br>    <br>    def breathe(self):<br>        return f&quot;{self.name} is breathing&quot;<br><br><br>class Mammal(Animal):<br>    def __init__(self, name):<br>        super().__init__(name)<br>        self.warm_blooded = True<br>        print(&quot;Mammal.__init__ called&quot;)<br>    <br>    def give_milk(self):<br>        return f&quot;{self.name} produces milk&quot;<br>class Bird(Animal):<br>    def __init__(self, name):<br>        super().__init__(name)<br>        self.has_wings = True<br>        print(&quot;Bird.__init__ called&quot;)<br>    <br>    def lay_eggs(self):<br>        return f&quot;{self.name} lays eggs&quot;<br><br><br># The diamond problem: Platypus inherits from both Mammal and Bird<br># But both Mammal and Bird inherit from Animal<br># Will Animal.__init__ be called twice?<br><br><br>class Platypus(Mammal, Bird):  # Diamond inheritance!<br>    def __init__(self, name):<br>        # This is the problematic way (calls Animal.__init__ twice)<br>        Mammal.__init__(self, name)  # Calls Animal.__init__<br>        Bird.__init__(self, name)    # Calls Animal.__init__ AGAIN!<br>        print(&quot;Platypus.__init__ called&quot;)<br><br><br># Test the diamond problem<br>print(&quot;\n=== Diamond Problem (Wrong Way) ===&quot;)<br>platypus = Platypus(&quot;Perry&quot;)<br># Notice Animal.__init__ gets called twice!<br>print(f&quot;\nPlatypus MRO: {[cls.__name__ for cls in Platypus.mro()]}&quot;)<br># [Platypus, Mammal, Bird, Animal, object]</pre><h3>Key Takeaways</h3><h3>1. Multiple Inheritance Syntax</h3><pre>class Child(Parent1, Parent2, Parent3):<br>    pass  # Inherits from all parents</pre><h3>2. MRO Determines Method Resolution</h3><pre>print(Child.mro())  # Shows the order Python searches for methods</pre><h3>3. First Found Wins</h3><pre># If Parent1 and Parent2 both have same_method(),<br># Parent1&#39;s version is used (comes first in MRO)<br>child.same_method()  # Calls Parent1.same_method()</pre><h3>4. Manual Constructor Calls</h3><pre>class Child(Parent1, Parent2):<br>    def __init__(self, args):<br>        Parent1.__init__(self, args1)<br>        Parent2.__init__(self, args2)</pre><h3>5. Diamond Problem Exists</h3><pre># When parents share a common ancestor,<br># the ancestor&#39;s methods might be called multiple times</pre><h3>The super() Solution — Cooperative Inheritance</h3><h3>The Problem We’re Solving</h3><p>Remember our Diamond Problem where Animal.__init__ got called twice? Let’s fix that with the power of super()!</p><h3>Understanding What super() Really Does</h3><p>Most people think super() means “call parent method.” That’s WRONG!</p><p><strong>super() means: &quot;Call the NEXT method in the MRO chain&quot;</strong></p><p>Let’s see this in action:</p><pre>class A:<br>    def __init__(self):<br>        print(&quot;A.__init__&quot;)<br>        self.value = &quot;A&quot;<br><br>class B(A):<br>    def __init__(self):<br>        print(&quot;B.__init__ - before super()&quot;)<br>        super().__init__()  # This doesn&#39;t call A.__init__ directly!<br>        print(&quot;B.__init__ - after super()&quot;)<br>        self.value += &quot;B&quot;<br><br>class C(A):<br>    def __init__(self):<br>        print(&quot;C.__init__ - before super()&quot;)<br>        super().__init__()  # This doesn&#39;t call A.__init__ directly!<br>        print(&quot;C.__init__ - after super()&quot;)<br>        self.value += &quot;C&quot;<br><br>class D(B, C):  # Multiple inheritance - the diamond!<br>    def __init__(self):<br>        print(&quot;D.__init__ - before super()&quot;)<br>        super().__init__()  # This is the magic!<br>        print(&quot;D.__init__ - after super()&quot;)<br>        self.value += &quot;D&quot;<br><br># Let&#39;s see what happens<br>print(&quot;=== The super() Magic ===&quot;)<br>print(&quot;D.mro():&quot;, [cls.__name__ for cls in D.mro()])<br># [D, B, C, A, object]<br>print(&quot;\nCreating D instance:&quot;)<br>d = D()<br>print(f&quot;Final value: {d.value}&quot;)<br></pre><h3>The Flow: How super() Actually Works</h3><pre># When you create D():<br>d = D()<br><br># Python does this automatically:<br># 1. &quot;Call D.__init__()&quot;<br># 2. &quot;D.__init__ calls super().__init__()&quot;<br># 3. &quot;D&#39;s MRO is [D, B, C, A, object]&quot;<br># 4. &quot;Current class is D, next in MRO is B&quot;<br># 5. &quot;Call B.__init__()&quot;<br># 6. &quot;B.__init__ calls super().__init__()&quot;<br># 7. &quot;Current class is B, next in MRO is C&quot;<br># 8. &quot;Call C.__init__()&quot;<br># 9. &quot;C.__init__ calls super().__init__()&quot;<br># 10. &quot;Current class is C, next in MRO is A&quot;<br># 11. &quot;Call A.__init__()&quot; (ONLY ONCE!)<br># 12. &quot;Work backwards: A finishes, C finishes, B finishes, D finishes&quot;</pre><h3>Cooperative Inheritance with **kwargs</h3><p>The professional way to handle multiple inheritance is with cooperative **kwargs:</p><pre>class Animal:<br>    def __init__(self, name, species, **kwargs):<br>        self.name = name<br>        self.species = species<br>        self.energy = 100<br>        # Pass any remaining kwargs to the next class in MRO<br>        super().__init__(**kwargs)<br>        print(f&quot;Animal.__init__ for {name}&quot;)<br><br>class Flyable:<br>    def __init__(self, max_altitude=1000, **kwargs):<br>        self.can_fly = True<br>        self.altitude = 0<br>        self.max_altitude = max_altitude<br>        # Continue the super() chain<br>        super().__init__(**kwargs)<br>        print(&quot;Flyable.__init__ called&quot;)<br>    <br>    def fly(self):<br>        if not self.can_fly:<br>            return &quot;Cannot fly!&quot;<br>        <br>        self.altitude = min(self.altitude + 100, self.max_altitude)<br>        return f&quot;Flying at {self.altitude} feet&quot;<br>    <br>    def land(self):<br>        self.altitude = 0<br>        return &quot;Landed safely&quot;<br><br>class Swimmable:<br>    def __init__(self, max_depth=50, **kwargs):<br>        self.can_swim = True<br>        self.depth = 0<br>        self.max_depth = max_depth<br>        # Continue the super() chain<br>        super().__init__(**kwargs)<br>        print(&quot;Swimmable.__init__ called&quot;)<br>    <br>    def swim(self):<br>        if not self.can_swim:<br>            return &quot;Cannot swim!&quot;<br>        <br>        self.depth = min(self.depth + 10, self.max_depth)<br>        return f&quot;Swimming at {self.depth} feet deep&quot;<br>    <br>    def surface(self):<br>        self.depth = 0<br>        return &quot;Surfaced&quot;<br><br>class Walkable:<br>    def __init__(self, max_speed=20, **kwargs):<br>        self.can_walk = True<br>        self.steps = 0<br>        self.max_speed = max_speed<br>        # Continue the super() chain<br>        super().__init__(**kwargs)<br>        print(&quot;Walkable.__init__ called&quot;)<br>    <br>    def walk(self):<br>        if not self.can_walk:<br>            return &quot;Cannot walk!&quot;<br>        <br>        self.steps += self.max_speed<br>        return f&quot;Walking at {self.max_speed} mph... {self.steps} steps total&quot;<br># Now the magic happens!<br><br>class Duck(Animal, Flyable, Swimmable, Walkable):<br>    def __init__(self, name, **kwargs):<br>        # ONE super() call handles EVERYTHING!<br>        super().__init__(<br>            name=name, <br>            species=&quot;Duck&quot;,<br>            max_altitude=500,  # Duck-specific flying limit<br>            max_depth=20,      # Duck-specific diving limit  <br>            max_speed=10,      # Duck-specific walking speed<br>            **kwargs<br>        )<br>        print(&quot;Duck.__init__ called&quot;)<br>    <br>    def make_sound(self):<br>        return &quot;Quack! Quack!&quot;<br><br># Test cooperative inheritance<br>print(&quot;\n=== Cooperative Inheritance with super() ===&quot;)<br>print(&quot;Duck MRO:&quot;, [cls.__name__ for cls in Duck.mro()])<br>print(&quot;\nCreating Duck:&quot;)<br>duck = Duck(&quot;Daffy&quot;)<br>print(f&quot;\nDuck created: {duck.name} the {duck.species}&quot;)<br>print(f&quot;Max altitude: {duck.max_altitude}&quot;)<br>print(f&quot;Max depth: {duck.max_depth}&quot;)  <br>print(f&quot;Max walking speed: {duck.max_speed}&quot;)</pre><h3>The Flow: Cooperative Inheritance</h3><pre># When you write this:<br>duck = Duck(&quot;Daffy&quot;)<br><br># Python does this automatically:<br># 1. &quot;Call Duck.__init__(&#39;Daffy&#39;)&quot;<br># 2. &quot;Duck calls super().__init__(name=&#39;Daffy&#39;, species=&#39;Duck&#39;, ...)&quot;<br># 3. &quot;Duck&#39;s MRO: [Duck, Animal, Flyable, Swimmable, Walkable, object]&quot;<br># 4. &quot;Next after Duck is Animal, call Animal.__init__()&quot;<br># 5. &quot;Animal extracts name=&#39;Daffy&#39;, species=&#39;Duck&#39;, passes rest to super()&quot;<br># 6. &quot;Next after Animal is Flyable, call Flyable.__init__()&quot;<br># 7. &quot;Flyable extracts max_altitude=500, passes rest to super()&quot;<br># 8. &quot;Next after Flyable is Swimmable, call Swimmable.__init__()&quot;<br># 9. &quot;Swimmable extracts max_depth=20, passes rest to super()&quot;<br># 10. &quot;Next after Swimmable is Walkable, call Walkable.__init__()&quot;<br># 11. &quot;Walkable extracts max_speed=10, passes rest to super()&quot;<br># 12. &quot;Next after Walkable is object, call object.__init__()&quot;<br># 13. &quot;Chain complete - each class initialized EXACTLY ONCE!&quot;</pre><h3>The Diamond Problem — SOLVED!</h3><p>Let’s revisit our diamond problem with the super() solution:</p><pre>class Animal:<br>    def __init__(self, name, **kwargs):<br>        self.name = name<br>        super().__init__(**kwargs)<br>        print(f&quot;Animal.__init__ for {name}&quot;)<br>    <br>    def breathe(self):<br>        return f&quot;{self.name} is breathing&quot;<br><br><br>class Mammal(Animal):<br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        self.warm_blooded = True<br>        print(&quot;Mammal.__init__&quot;)<br>    <br>    def give_milk(self):<br>        return f&quot;{self.name} produces milk&quot;<br><br>class Bird(Animal):<br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        self.has_wings = True<br>        print(&quot;Bird.__init__&quot;)<br>    <br>    def lay_eggs(self):<br>        return f&quot;{self.name} lays eggs&quot;<br><br>class Platypus(Mammal, Bird):<br>    def __init__(self, name, **kwargs):<br>        # ONE super() call handles the entire diamond!<br>        super().__init__(name=name, **kwargs)<br>        print(&quot;Platypus.__init__&quot;)<br>    <br>    def __str__(self):<br>        abilities = []<br>        if self.warm_blooded:<br>            abilities.append(&quot;produces milk&quot;)<br>        if self.has_wings:<br>            abilities.append(&quot;has wings&quot;)<br>        return f&quot;{self.name} the Platypus: {&#39;, &#39;.join(abilities)}&quot;<br><br><br># Test the diamond solution<br>print(&quot;\n=== Diamond Problem SOLVED ===&quot;)<br>print(&quot;Platypus MRO:&quot;, [cls.__name__ for cls in Platypus.mro()])<br># [Platypus, Mammal, Bird, Animal, object]<br>print(&quot;\nCreating Platypus:&quot;)<br>perry = Platypus(&quot;Perry&quot;)<br># Notice: Animal.__init__ is called ONLY ONCE!<br>print(f&quot;\nPlatypus created: {perry}&quot;)<br>print(f&quot;Breathes: {perry.breathe()}&quot;)<br>print(f&quot;Milk: {perry.give_milk()}&quot;)  <br>print(f&quot;Eggs: {perry.lay_eggs()}&quot;)</pre><h3>Key Insights You Now Understand</h3><h3>1. super() Follows MRO, Not Parent Class</h3><pre># super() doesn&#39;t mean &quot;call parent&quot;<br># super() means &quot;call next class in MRO&quot;<br>class Child(Parent1, Parent2):<br>    def method(self):<br>        super().method()  # Calls next in MRO, not necessarily Parent1</pre><h3>2. Cooperative Inheritance Pattern</h3><pre>class Mixin:<br>    def __init__(self, **kwargs):<br>        # Extract what you need<br>        self.my_attr = kwargs.pop(&#39;my_attr&#39;, &#39;default&#39;)<br>        # Pass the rest along<br>        super().__init__(**kwargs)</pre><h3>3. Diamond Problem Solution</h3><pre># Each class in the hierarchy gets called EXACTLY ONCE<br># No matter how complex the diamond, super() handles it</pre><h3>4. Method Chaining</h3><pre># Methods can cooperatively call each other<br>def method(self):<br>    result = super().method()  # Get result from next in chain<br>    return f&quot;My processing -&gt; {result}&quot;</pre><h3>Interview Questions You Can Now Answer</h3><h3>Q: “How does super() work in multiple inheritance?”</h3><p><strong>Your Answer:</strong> “super() doesn’t call the parent class directly. It calls the next class in the Method Resolution Order (MRO). This enables cooperative inheritance where each class in the hierarchy is called exactly once, even in complex diamond inheritance scenarios. The MRO is determined by Python’s C3 linearization algorithm.”</p><h3>Q: “What’s cooperative inheritance?”</h3><p><strong>Your Answer:</strong> “Cooperative inheritance is a pattern where each class in an inheritance chain uses super() to call the next class in the MRO, and uses **kwargs to pass along parameters. This ensures all classes are properly initialized exactly once, and methods can be chained together cooperatively.”</p><h3>Q: “How does Python solve the diamond problem?”</h3><p><strong>Your Answer:</strong> “Python uses MRO and cooperative inheritance with super(). Even when a class inherits from multiple parents that share a common ancestor, the MRO ensures each class appears exactly once in the resolution order, and super() follows this order precisely.”</p><h3>What You’ve Mastered</h3><p>You now understand:<br>✅ <strong>How super() really works</strong> (MRO, not parent)<br>✅ <strong>Cooperative inheritance</strong> (the professional pattern)<br>✅ <strong>Diamond problem solution</strong> (no duplicate calls)<br>✅ <strong>Method chaining</strong> (cooperative method calls)<br>✅ <strong>Real-world patterns</strong> (Django-style mixins)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=934337ff58d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/python-inheritance-mro-the-complete-guide-934337ff58d4">Python Inheritance &amp; MRO: The Complete Guide</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Encapsulation: Why Properties Beat Getter/Setter Methods]]></title>
            <link>https://medium.com/codex/python-encapsulation-why-properties-beat-getter-setter-methods-88ff1e58a0d5?source=rss-b56cc0fb5911------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ff1e58a0d5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Satyam Warghat]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 18:13:57 GMT</pubDate>
            <atom:updated>2025-09-04T12:00:42.209Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how Python’s approach to encapsulation differs from other languages and why it’s actually more powerful</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61p1r4N3rSW-mL8lBbp_Ug.png" /></figure><h3>Introduction</h3><p>If you’re coming from languages like Java or C++, Python’s approach to encapsulation might seem… weird. Where are the private and public keywords? Why can I still access &quot;private&quot; variables? Is Python even doing encapsulation properly?</p><p>The short answer: <strong>Yes, but it’s doing it the Python way.</strong></p><p>In this comprehensive guide, we’ll explore Python’s unique philosophy on encapsulation, understand why it works, and learn to write professional-grade Python code that follows best practices.</p><h3>What is Encapsulation?</h3><p>Encapsulation is one of the four pillars of Object-Oriented Programming. At its core, it’s about:</p><ol><li><strong>Bundling data and methods</strong> that operate on that data into a single unit (class)</li><li><strong>Controlling access</strong> to that data to prevent misuse</li><li><strong>Hiding implementation details</strong> from the outside world</li></ol><p>But here’s where Python gets interesting — it achieves these goals through <strong>convention and trust</strong> rather than <strong>enforcement and restriction</strong>.</p><h3>The Evolution: From Basic to Pythonic</h3><h3>Basic Encapsulation (The Old Way)</h3><p>Let’s start with how you might implement encapsulation in traditional OOP style:</p><pre>class BankAccount:<br>    def __init__(self, account_number, balance):<br>        # Manually create &quot;private&quot; attributes<br>        self._account_number = account_number<br>        self._balance = balance<br>    <br>    # Getter methods<br>    def get_account_number(self):<br>        return self._account_number<br>    <br>    def get_balance(self):<br>        return self._balance<br>    <br>    # Setter methods with validation<br>    def set_balance(self, amount):<br>        if amount &lt; 0:<br>            raise ValueError(&quot;Balance cannot be negative&quot;)<br>        self._balance = amount<br>    <br>    def set_account_number(self, account_number):<br>        if not account_number:<br>            raise ValueError(&quot;Account number cannot be empty&quot;)<br>        self._account_number = account_number</pre><pre># Usage - verbose and clunky<br>account = BankAccount(&quot;12345&quot;, 1000)<br>print(account.get_balance())  # Need to call method<br>account.set_balance(1500)     # Need to call method</pre><p><strong>Problems with this approach:</strong></p><ul><li>Verbose method calls (get_balance(), set_balance())</li><li>No validation during object creation</li><li>Can bypass validation by accessing _balance directly</li><li>Not very “Pythonic”</li></ul><h3>Pythonic Encapsulation (The Modern Way)</h3><p>Now let’s see how Python professionals handle this:</p><pre>class BankAccount:<br>    def __init__(self, account_number, balance):<br>        # Use properties - validation happens automatically!<br>        self.account_number = account_number<br>        self.balance = balance<br>    <br>    @property<br>    def account_number(self):<br>        return self._account_number<br>    <br>    @account_number.setter<br>    def account_number(self, value):<br>        if not value:<br>            raise ValueError(&quot;Account number cannot be empty&quot;)<br>        self._account_number = value<br>    <br>    @property<br>    def balance(self):<br>        return self._balance<br>    <br>    @balance.setter<br>    def balance(self, value):<br>        if value &lt; 0:<br>            raise ValueError(&quot;Balance cannot be negative&quot;)<br>        self._balance = value</pre><pre># Usage - clean and natural<br>account = BankAccount(&quot;12345&quot;, 1000)  # Validation happens here!<br>print(account.balance)                # Natural attribute access<br>account.balance = 1500               # Natural assignment</pre><h3>The Magic Behind Properties</h3><p>The beauty of Python properties is in how seamlessly they work. Let’s break down what happens behind the scenes:</p><h3>When You Create an Object:</h3><pre># When you write this in __init__:<br>self.balance = 1000</pre><pre># Python does this automatically:<br># 1. &quot;I see assignment to &#39;balance&#39;&quot;<br># 2. &quot;Let me look for a @balance.setter&quot;<br># 3. &quot;Found it! Calling the setter method&quot;<br># 4. &quot;Setter validates and creates self._balance = 1000&quot;<br># 5. &quot;Done!&quot;</pre><h3>When You Access a Property:</h3><pre># When you write this:<br>print(account.balance)</pre><pre># Python does this automatically:<br># 1. &quot;I see access to &#39;balance&#39;&quot;<br># 2. &quot;Let me look for a @property getter&quot;<br># 3. &quot;Found it! Calling the getter method&quot;<br># 4. &quot;Getter returns self._balance&quot;<br># 5. &quot;Done!&quot;</pre><h3>When You Modify a Property:</h3><pre># When you write this:<br>account.balance = 2000</pre><pre># Python does this automatically:<br># 1. &quot;I see assignment to &#39;balance&#39;&quot;<br># 2. &quot;Let me look for a @balance.setter&quot;<br># 3. &quot;Found it! Calling the setter method&quot;<br># 4. &quot;Setter validates the value&quot;<br># 5. &quot;If valid, setter updates self._balance = 2000&quot;<br># 6. &quot;Done!&quot;</pre><h3>The Secret: Storage Variables vs Property Names</h3><p>One crucial concept that often confuses beginners is the relationship between the property name and where the data is actually stored.</p><pre>class Temperature:<br>    def __init__(self, celsius):<br>        self.celsius = celsius  # This uses the setter<br>    <br>    @property<br>    def celsius(self):<br>        # This accesses the STORAGE variable<br>        return self._celsius<br>    <br>    @celsius.setter<br>    def celsius(self, value):<br>        if value &lt; -273.15:<br>            raise ValueError(&quot;Temperature below absolute zero!&quot;)<br>        # This creates/updates the STORAGE variable<br>        self._celsius = value</pre><pre># The pattern:<br># - Property name: celsius (what users see)<br># - Storage variable: _celsius (where data lives)</pre><h3>Common Pitfalls and How to Avoid Them</h3><h3>Pitfall 1: Infinite Recursion</h3><pre># WRONG - This causes infinite recursion!<br>@property<br>def balance(self):<br>    return self.balance  # Calls itself forever!</pre><pre># CORRECT - Return the storage variable<br>@property<br>def balance(self):<br>    return self._balance  # Returns actual data</pre><h3>Pitfall 2: Forgetting to Use Properties in init</h3><pre># WRONG - Bypasses validation during creation<br>def __init__(self, balance):<br>    self._balance = balance  # Direct assignment, no validation!</pre><pre># CORRECT - Uses validation during creation<br>def __init__(self, balance):<br>    self.balance = balance  # Goes through setter validation</pre><h3>Pitfall 3: Returning from Setters</h3><pre># WRONG - Setters shouldn&#39;t return values<br>@balance.setter<br>def balance(self, value):<br>    self._balance = value<br>    return self._balance  # Don&#39;t do this!</pre><pre># CORRECT - Setters just set<br>@balance.setter<br>def balance(self, value):<br>    self._balance = value  # Just set the value</pre><h3>Python’s Philosophy: “We’re All Consenting Adults”</h3><p>Now, let’s address the elephant in the room. You might notice that you can still access the “private” variables:</p><pre>account = BankAccount(&quot;12345&quot;, 1000)</pre><pre># The proper way:<br>print(account.balance)    # 1000 - Goes through getter</pre><pre># The &quot;backdoor&quot; way:<br>print(account._balance)   # 1000 - Direct access, but allowed!</pre><p><strong>“Wait, isn’t this breaking encapsulation?”</strong></p><p>Not really. Python’s approach is different from languages like Java or C++. Here’s Python’s philosophy:</p><ul><li><strong>Convention over Enforcement</strong>: The underscore _balance means &quot;this is internal, be careful&quot;</li><li><strong>Trust over Restriction</strong>: Python trusts developers to use the proper API</li><li><strong>Practicality over Purity</strong>: Sometimes you need access for debugging or testing</li></ul><h3>The Three Levels of Privacy in Python</h3><p>Python offers three levels of privacy through naming conventions:</p><h3>1. Public (balance)</h3><pre>class Account:<br>    def __init__(self):<br>        self.balance = 1000  # Public - use freely</pre><pre>account = Account()<br>print(account.balance)  # Perfectly fine</pre><h3>2. Protected (_balance)</h3><pre>class Account:<br>    def __init__(self):<br>        self._balance = 1000  # Protected - internal use</pre><pre>account = Account()<br>print(account._balance)  # Allowed but discouraged</pre><h3>3. Private (__balance)</h3><pre>class Account:<br>    def __init__(self):<br>        self.__balance = 1000  # Private - name mangling applied</pre><pre>account = Account()<br>print(account.__balance)  # AttributeError!<br>print(account._Account__balance)  # Works but obviously wrong</pre><h3>Real-World Example: E-Commerce Product</h3><p>Let’s build a more comprehensive example that showcases encapsulation in action:</p><pre>class Product:<br>    def __init__(self, name, base_price, discount_percent=0):<br>        self.name = name<br>        self.base_price = base_price<br>        self.discount_percent = discount_percent<br>        self._inventory_count = 0<br>        self._is_active = True<br>    <br>    @property<br>    def name(self):<br>        return self._name<br>    <br>    @name.setter<br>    def name(self, value):<br>        if not isinstance(value, str) or len(value.strip()) == 0:<br>            raise ValueError(&quot;Product name must be a non-empty string&quot;)<br>        self._name = value.strip().title()<br>    <br>    @property<br>    def base_price(self):<br>        return self._base_price<br>    <br>    @base_price.setter<br>    def base_price(self, value):<br>        if not isinstance(value, (int, float)) or value &lt;= 0:<br>            raise ValueError(&quot;Base price must be a positive number&quot;)<br>        self._base_price = round(float(value), 2)<br>    <br>    @property<br>    def discount_percent(self):<br>        return self._discount_percent<br>    <br>    @discount_percent.setter<br>    def discount_percent(self, value):<br>        if not isinstance(value, (int, float)):<br>            raise TypeError(&quot;Discount must be a number&quot;)<br>        if not (0 &lt;= value &lt;= 100):<br>            raise ValueError(&quot;Discount must be between 0 and 100&quot;)<br>        self._discount_percent = value<br>    <br>    @property<br>    def current_price(self):<br>        &quot;&quot;&quot;Computed property - automatically calculated&quot;&quot;&quot;<br>        discount_amount = (self._base_price * self._discount_percent) / 100<br>        return round(self._base_price - discount_amount, 2)<br>    <br>    @property<br>    def savings(self):<br>        &quot;&quot;&quot;Another computed property&quot;&quot;&quot;<br>        return round(self._base_price - self.current_price, 2)<br>    <br>    @property<br>    def inventory_count(self):<br>        return self._inventory_count<br>    <br>    @inventory_count.setter<br>    def inventory_count(self, value):<br>        if not isinstance(value, int) or value &lt; 0:<br>            raise ValueError(&quot;Inventory count must be a non-negative integer&quot;)<br>        self._inventory_count = value<br>    <br>    @property<br>    def is_in_stock(self):<br>        &quot;&quot;&quot;Computed property with business logic&quot;&quot;&quot;<br>        return self._inventory_count &gt; 0 and self._is_active<br>    <br>    @property<br>    def stock_status(self):<br>        &quot;&quot;&quot;Complex computed property&quot;&quot;&quot;<br>        if not self._is_active:<br>            return &quot;Discontinued&quot;<br>        elif self._inventory_count == 0:<br>            return &quot;Out of Stock&quot;<br>        elif self._inventory_count &lt; 5:<br>            return &quot;Low Stock&quot;<br>        else:<br>            return &quot;In Stock&quot;<br>    <br>    def __str__(self):<br>        return f&quot;{self.name}: ${self.current_price} ({self.stock_status})&quot;</pre><pre># Usage example<br>product = Product(&quot;Wireless Headphones&quot;, 99.99, 15)<br>product.inventory_count = 3</pre><pre>print(f&quot;Product: {product.name}&quot;)<br>print(f&quot;Original Price: ${product.base_price}&quot;)<br>print(f&quot;Current Price: ${product.current_price}&quot;)<br>print(f&quot;You Save: ${product.savings}&quot;)<br>print(f&quot;Stock Status: {product.stock_status}&quot;)<br>print(f&quot;In Stock: {product.is_in_stock}&quot;)</pre><pre># Dynamic updates work seamlessly<br>product.discount_percent = 25<br>print(f&quot;New Price: ${product.current_price}&quot;)  # Automatically recalculated!</pre><h3>When to Use Properties vs Simple Attributes</h3><p><strong>Use simple attributes when:</strong></p><ul><li>No validation needed</li><li>No computation required</li><li>Direct access is sufficient</li></ul><pre>class Person:<br>    def __init__(self, name):<br>        self.name = name  # Simple attribute is fine</pre><p><strong>Use properties when:</strong></p><ul><li>Validation is required</li><li>Values are computed</li><li>You need to maintain backwards compatibility</li><li>You want to add logging or side effects</li></ul><pre>class Circle:<br>    def __init__(self, radius):<br>        self.radius = radius  # Uses property for validation<br>    <br>    @property<br>    def radius(self):<br>        return self._radius<br>    <br>    @radius.setter  <br>    def radius(self, value):<br>        if value &lt;= 0:<br>            raise ValueError(&quot;Radius must be positive&quot;)<br>        self._radius = value<br>    <br>    @property<br>    def area(self):<br>        return 3.14159 * self._radius ** 2  # Computed property</pre><h3>Best Practices for Python Encapsulation</h3><h3>1. Start Simple, Add Properties When Needed</h3><pre># Start with simple attributes<br>class User:<br>    def __init__(self, email):<br>        self.email = email</pre><pre># Later, add validation without breaking existing code<br>class User:<br>    def __init__(self, email):<br>        self.email = email  # Now uses property<br>    <br>    @property<br>    def email(self):<br>        return self._email<br>    <br>    @email.setter<br>    def email(self, value):<br>        if &#39;@&#39; not in value:<br>            raise ValueError(&quot;Invalid email&quot;)<br>        self._email = value</pre><h3>2. Use Descriptive Error Messages</h3><pre>@price.setter<br>def price(self, value):<br>    if not isinstance(value, (int, float)):<br>        raise TypeError(f&quot;Price must be a number, got {type(value).__name__}&quot;)<br>    if value &lt;= 0:<br>        raise ValueError(f&quot;Price must be positive, got {value}&quot;)<br>    self._price = value</pre><h3>3. Consider Performance for Computed Properties</h3><pre>class DataAnalyzer:<br>    def __init__(self, data):<br>        self._data = data<br>        self._stats_cache = None<br>        self._data_version = 1<br>    <br>    @property<br>    def data(self):<br>        return self._data<br>    <br>    @data.setter<br>    def data(self, value):<br>        self._data = value<br>        self._data_version += 1  # Invalidate cache<br>        self._stats_cache = None<br>    <br>    @property<br>    def statistics(self):<br>        # Expensive computation with caching<br>        if (self._stats_cache is None or <br>            self._stats_cache[&#39;version&#39;] != self._data_version):<br>            <br>            self._stats_cache = {<br>                &#39;mean&#39;: sum(self._data) / len(self._data),<br>                &#39;max&#39;: max(self._data),<br>                &#39;version&#39;: self._data_version<br>            }<br>        <br>        return self._stats_cache</pre><h3>4. Use Type Hints for Better Code Documentation</h3><pre>from typing import Union</pre><pre>class BankAccount:<br>    def __init__(self, account_number: str, balance: float):<br>        self.account_number = account_number<br>        self.balance = balance<br>    <br>    @property<br>    def balance(self) -&gt; float:<br>        return self._balance<br>    <br>    @balance.setter<br>    def balance(self, value: Union[int, float]) -&gt; None:<br>        if value &lt; 0:<br>            raise ValueError(&quot;Balance cannot be negative&quot;)<br>        self._balance = float(value)</pre><h3>Interview Questions and How to Answer Them</h3><h3>Q: “What’s the difference between balance and _balance?&quot;</h3><p><strong>Answer:</strong> “balance is the property interface that users interact with - it provides validation and controlled access. _balance is the storage variable where the actual data lives. The property acts as a smart gateway to the storage.&quot;</p><h3>Q: “Why can I still access _balance directly in Python?&quot;</h3><p><strong>Answer:</strong> “Python follows the philosophy ‘we’re all consenting adults.’ The underscore is a convention meaning ‘this is internal, use with caution.’ Python trusts developers to use the proper API (balance) but doesn&#39;t prevent access for legitimate needs like debugging or testing.&quot;</p><h3>Q: “How do properties help with backwards compatibility?”</h3><p><strong>Answer:</strong> “You can start with simple attributes and later add properties without breaking existing code. Users still write obj.attribute = value, but now you can add validation, logging, or computation behind the scenes.&quot;</p><h3>Q: “What’s the performance impact of properties?”</h3><p><strong>Answer:</strong> “Properties have minimal overhead for simple get/set operations. For expensive computations, you can add caching. The benefits of validation and clean APIs usually outweigh the tiny performance cost.”</p><h3>Common Patterns in Production Code</h3><h3>Configuration Classes</h3><pre>class DatabaseConfig:<br>    def __init__(self):<br>        self._host = &quot;localhost&quot;<br>        self._port = 5432<br>        self._ssl_enabled = False<br>    <br>    @property<br>    def connection_string(self):<br>        protocol = &quot;postgresql+ssl&quot; if self._ssl_enabled else &quot;postgresql&quot;<br>        return f&quot;{protocol}://{self._host}:{self._port}/mydb&quot;<br>    <br>    @property<br>    def port(self):<br>        return self._port<br>    <br>    @port.setter<br>    def port(self, value):<br>        if not (1 &lt;= value &lt;= 65535):<br>            raise ValueError(&quot;Port must be between 1 and 65535&quot;)<br>        self._port = value</pre><h3>Model Classes (Django-style)</h3><pre>class User:<br>    def __init__(self, username, email):<br>        self.username = username<br>        self.email = email<br>        self._last_login = None<br>    <br>    @property<br>    def display_name(self):<br>        return self.username.title()<br>    <br>    @property<br>    def is_active(self):<br>        from datetime import datetime, timedelta<br>        if self._last_login is None:<br>            return False<br>        return datetime.now() - self._last_login &lt; timedelta(days=30)</pre><h3>Conclusion</h3><p>Python’s approach to encapsulation might seem unusual at first, but it’s actually quite powerful. By combining:</p><ul><li><strong>Properties</strong> for clean, natural syntax</li><li><strong>Naming conventions</strong> for clear intent</li><li><strong>Trust and flexibility</strong> for practical needs</li></ul><p>Python achieves encapsulation that’s both protective and pragmatic.</p><p>The key takeaways:</p><ol><li><strong>Use properties for validation and computed values</strong></li><li><strong>Let setters handle object creation validation</strong></li><li><strong>Follow naming conventions (</strong><strong>_protected, </strong><strong>__private)</strong></li><li><strong>Trust other developers to use your API correctly</strong></li><li><strong>Start simple, add complexity when needed</strong></li></ol><p>Master these concepts, and you’ll write Python code that’s not just functional, but truly Pythonic. Your future self (and your teammates) will thank you!</p><p>Happy coding! 🐍✨</p><p>#Python #OOP #Programming</p><p><em>Found this helpful? Share it with other Python developers who are making the transition from basic to Pythonic encapsulation!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ff1e58a0d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/python-encapsulation-why-properties-beat-getter-setter-methods-88ff1e58a0d5">Python Encapsulation: Why Properties Beat Getter/Setter Methods</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>