Ever wondered how Python knows what to do when you use + between two objects? Or how len() works on your custom class? The answer lies in magic methods (also called dunder methods). These are special methods wrapped in double underscores, and they're what make Python feel like magic. Here are a few that changed how I write code: __init__ — The constructor everyone knows. But it's just the beginning. __repr__ & __str__ — Control how your object looks when printed or logged. Debugging becomes 10x easier when your objects speak for themselves. __len__, __getitem__, __iter__ — Make your custom class behave like a built-in list or dictionary. Your teammates won't even know the difference. __enter__ & __exit__ — Power behind the with statement. Perfect for managing resources like files, DB connections, and locks. __eq__, __lt__, __gt__ — Define what "equal" or "greater than" means for your objects. Sorting a list of custom objects? No problem. __call__ — Make an instance callable like a function. This one unlocks some seriously clean design patterns. The real power of magic methods isn't just the syntax — it's that they let you write intuitive, Pythonic APIs that feel native to the language. When your custom class supports len(), iteration, and comparison naturally, your code becomes easier to read, test, and maintain. What's your favorite magic method? Drop it in the comments #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #BackendDevelopment
Unlocking Python's Magic: Mastering Dunder Methods
More Relevant Posts
-
𝗦𝘁𝗼𝗽 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗶𝗸𝗲 𝗮 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 — 𝗗𝗼 𝗧𝗵𝗶𝘀 𝗜𝗻𝘀𝘁𝗲𝗮𝗱 I see this in code frequently. 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘄𝗵𝗼 𝗸𝗻𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗯𝘂𝘁 𝗮𝗿𝗲𝗻'𝘁 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻𝗶𝗰 𝗰𝗼𝗱𝗲. There's a difference between code that works and code that belongs in Python. Look at the two examples in the image. 𝗦𝗮𝗺𝗲 𝗼𝘂𝘁𝗽𝘂𝘁. 𝗕𝘂𝘁 𝗼𝗻𝗲 𝗿𝗲𝗮𝗱𝘀 𝗹𝗶𝗸𝗲 𝗮 𝘁𝗿𝗮𝗻𝘀𝗹𝗮𝘁𝗲𝗱 𝗖 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. The other reads like Python. Here are the patterns I see developers overuse and what to do instead: ❌ Manual index loops → ✅ enumerate() ❌ Building lists with .append() in loops → ✅ list comprehensions ❌ Checking "if len(x) > 0" → ✅ just "if x" ❌ Manual min/max logic → ✅ built-in min(), max() with key= ❌ Catching bare Exception → ✅ catch specific exceptions 𝗡𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 𝗮𝗿𝗲 𝗮𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗣𝘆𝘁𝗵𝗼𝗻. They're just Python being Python. When I started, I wrote Python like I was still thinking in C. It took real project work like building actual APIs and handling real data before these patterns became instinct. The shift happens when you stop learning syntax and start reading great Python code written by others. 𝗪𝗵𝗶𝗰𝗵 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 '𝗯𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗿𝗮𝗽𝘀' 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗳𝗮𝗹𝗹 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝗹𝗼𝗻𝗴𝗲𝘀𝘁 𝗯𝗲𝗳𝗼𝗿𝗲 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗯𝗿𝗲𝗮𝗸𝗶𝗻𝗴 𝘁𝗵𝗲 𝗵𝗮𝗯𝗶𝘁? #Python #PythonTips #CleanCode #BackendDevelopment #LearnPython #SoftwareEngineering
To view or add a comment, sign in
-
-
𝐍𝐮𝐦𝐏𝐲 𝐁𝐨𝐨𝐥𝐞𝐚𝐧 𝐓𝐫𝐚𝐩 I’m still at the very beginning of my Python journey. But even with my tiny amount of experience, I already hit a subtle NumPy trap that can easily sneak into real code. Python is full of surprises — even at the very beginning It happens when you create an untyped NumPy array and fill it with a function that should return booleans… …but sometimes returns 𝙉𝙤𝙣𝙚 when processing fails. At first, you expect a clean boolean array — because the function normally returns 𝙏𝙧𝙪𝙚 or 𝙁𝙖𝙡𝙨𝙚. But NumPy has other plans. Here’s the trap 👇 🟥 𝟏) 𝐔𝐧𝐭𝐲𝐩𝐞𝐝 𝐚𝐫𝐫𝐚𝐲 + 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐭𝐡𝐚𝐭 “𝐬𝐡𝐨𝐮𝐥𝐝” 𝐫𝐞𝐭𝐮𝐫𝐧 𝐛𝐨𝐨𝐥𝐞𝐚𝐧𝐬 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10) # 𝒏𝒐 𝒅𝒕𝒚𝒑𝒆 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() # 𝑻𝒓𝒖𝒆 / 𝑭𝒂𝒍𝒔𝒆 ... 𝒐𝒓 𝑵𝒐𝒏𝒆 You expect a clean boolean array because the function usually returns 𝙏𝙧𝙪𝙚/𝙁𝙖𝙡𝙨𝙚. But if even one value is 𝙉𝙤𝙣𝙚, NumPy must pick a type that can hold all values. 🟦 𝟐) 𝐍𝐮𝐦𝐏𝐲 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐬𝐰𝐢𝐭𝐜𝐡𝐞𝐬 𝐭𝐨 𝐝𝐭𝐲𝐩𝐞=𝐨𝐛𝐣𝐞𝐜𝐭 𝒂𝒓𝒓𝒂𝒚([𝑻𝒓𝒖𝒆, 𝑭𝒂𝒍𝒔𝒆, 𝑵𝒐𝒏𝒆, ...], 𝒅𝒕𝒚𝒑𝒆=𝒐𝒃𝒋𝒆𝒄𝒕) Impact: no vectorization logical operations break masks behave unpredictably performance collapses You think you have a NumPy boolean array. You actually have a Python object array. 🟩 𝟑) 𝐓𝐡𝐞 𝐬𝐢𝐥𝐞𝐧𝐭 𝐜𝐨𝐧𝐯𝐞𝐫𝐬𝐢𝐨𝐧 𝐭𝐫𝐚𝐩 Trying to fix it: 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10, 𝒅𝒕𝒚𝒑𝒆=𝒃𝒐𝒐𝒍) 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() NumPy converts: 𝑵𝒐𝒏𝒆 → 𝑭𝒂𝒍𝒔𝒆 (silently) Impact: 👉you lose the meaning of “no result” 👉your data becomes wrong 👉the bug becomes invisible ⭐ 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Same code. Same function. Two completely different arrays. NumPy’s dtype inference can hide subtle bugs — and I found this one with almost no Python experience. 𝐂𝐮𝐫𝐢𝐨𝐮𝐬 𝐭𝐨 𝐤𝐧𝐨𝐰: 👉 Have you ever run into this behavior? 👉 Or another NumPy dtype surprise? #python #numpy #datascience #cleanCode #devTips #programming
To view or add a comment, sign in
-
-
Python Portal: Use itertools instead of loops While loops are great, they have limitations, especially in modern programming styles and for certain types of problems. Understanding these limitations helps you choose the right tool for the task. Each loop iteration in Python incurs interpreter overhead, such as type checking and memory management. This can add up significantly on large datasets. To get around this limitation, Python has a convenient built-in library, itertools. For example, suppose you need to generate all unique pairs from a given list. Order is unimportant, and no element should be paired with itself. To avoid code bloat and reduce the risk of bugs, you can use the itertools library. The itertools.combinations() function directly generates all unique combinations of elements from an iterable, without repetition or order. Here's how you can rewrite the code using combinations from itertools: from itertools import combinations def get_unique_pairs_itertools(items): return list(combinations(items, 2)) my_list = ['A', 'B', 'C', 'D'] print(get_unique_pairs_itertools(my_list)) Output: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')] Original: https://lnkd.in/dRUUNewb
To view or add a comment, sign in
-
Ever feel like your code is "doing the work" but then immediately forgetting everything it just did? 🧠 If you’re a beginner learning Python, the difference between print and return is one of the biggest "Aha!" moments you'll have. Here is the breakdown using your example. 1. The "Show-and-Tell" (print) When you use print, the function calculates the answer and shouts it out to the console so you can see it. But that's it. It doesn't "save" the answer anywhere. Python def adding(a, b): print(a + b) adding(20, 12) # Output: 32 Think of it like: A chef cooking a meal, showing it to you, and then immediately throwing it in the trash. You saw it, but you can't eat it (or use it) later! 2. The "Hand-off" (return) When you use return, the function calculates the answer and hands it back to you. Now, you can store that answer in a variable and keep using it for other things. Python def adding_return(a, b): return a + b # We catch the value in a variable called 'result' result = adding_return(20, 12) # Now we can actually use it! print(result - 10) # Output: 22 Think of it like: A chef cooking a meal and putting it in a takeout box for you. You can take it home, add extra salt, or save it for tomorrow. 🔑 The Key Difference print is for Humans. It helps us see what’s happening during debugging. return is for Code. It allows different parts of your program to talk to each other and pass data around. Why this matters: If you tried to do adding(20, 12) - 10 with the first function, Python would give you an error. Why? Because the function didn't "give" you anything back to subtract from! #Python #CodingTips #LearnToCode #ProgrammingBeginner #SoftwareDevelopment #PythonBasics #TechEducation
To view or add a comment, sign in
-
⁉️ Have you ever actually thought about what __name__ == "__main__" means? Most of us wrote it the first time because a tutorial said so. Today I was structuring a small backend service in Python. Nothing flashy yet, just defining the application entry point. And that familiar line showed up again: ✳️ if __name__ == "__main__": It’s simple, but it solves an important architectural problem. In Python, every file is a module. When you execute a file directly: ✳️ python app.py Python assigns: ✳️ __name__ = "__main__" But when the same file is imported somewhere else: ✳️ import app Now: ✳️ __name__ = "__app__" That difference determines whether certain blocks of code run or stay dormant. Why is that useful? Because it lets you: • Keep runtime logic separate from reusable logic • Prevent accidental execution when modules are imported • Define a clear entry point for your application • Expose objects (like a Flask/FastAPI app instance) without auto-starting the server Without this guard, importing a module could trigger execution unintentionally — which becomes messy in larger systems. It’s one of those small Python conventions that quietly enforces better structure. Not flashy. But foundational. #Python #BackendDevelopment #SoftwareEngineering #Architecture
To view or add a comment, sign in
-
-
Building logic in Python isn’t always as simple as it looks. This visual captures a moment every developer has experienced — staring at a screen full of if, elif, else, and boolean conditions, wondering why something that seemed so clear in your head suddenly feels tangled. On one side, you see the chaos: overlapping thoughts, scattered conditions, and that familiar “Where did this go wrong?” moment. On the other side, there’s structure — a clean flowchart that reminds us that good logic isn’t about writing more code, but about thinking clearly before we write it. The contrast tells a powerful story: messy logic isn’t a lack of skill — it’s usually a lack of structure. Once we break problems down step-by-step and map decisions properly, everything starts to make sense. Every programmer moves from confusion to clarity. The key is slowing down, visualizing the flow, and trusting the process. If you’ve ever struggled with conditional statements or boolean logic in Python, you’re not alone — it’s part of the journey toward becoming a better problem solver. #DataAnalystLearningJourney
To view or add a comment, sign in
-
-
One-Line Sorting with Custom Lambda Key (Sort Integers by The Number of 1 Bits) 💯 || O(N log N) || Just tackled a fun bit-manipulation and sorting problem on LeetCode (Problem 1356), and I wanted to share a super clean, Pythonic way to solve it! 🐍 🎯 The Problem: Sort an array of integers based on the number of 1s in their binary representation. If two numbers have the same number of 1s, sort them by their decimal value. 💡 The Approach: Instead of writing a complex custom comparator, Python’s built-in sorting handles multi-level conditions beautifully. By passing a list [primary_condition, secondary_condition] to the key argument, Python sorts by the first element and automatically falls back to the second if there's a tie. Here is the one-liner: Python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: [bin(x).count('1'), x]) 📊 Complexity: Time: O(N log N) — Python's Timsort algorithm does the heavy lifting, and counting bits for 32-bit integers takes O(1) time. Space: O(N) — Using sorted() creates a new list. Pro-Tip: If you want to optimize for space, you can swap sorted(arr, ...) for arr.sort(...) to sort the array in-place! What is your favorite Python built-in function or one-liner tip? Let me know in the comments! 👇 #Python #LeetCode #Algorithms #CodingInterviews #SoftwareEngineering #DataStructures
To view or add a comment, sign in
-
Day 2 of my Python journey🐍 Today I moved from basic syntax to handling user interaction and manipulating data. I applied these new concepts by writing a basic terminal-based calculator script. 🖥️ Here is a straightforward breakdown of the Day 2 concepts from the CodeWithHarry playlist: ⌨️ User Input: Learned to use the built-in input() function to capture data directly from the terminal console. 🔄 Typecasting: Coming from a JavaScript background where types are often coerced automatically, Python is stricter. I learned that inputs are received as strings by default and must be explicitly converted using functions like int() or float() before performing calculations. ✂️ String Slicing & Methods: Explored how Python handles text data, specifically using bracket syntax [start:end] for slicing, which is a clean and efficient way to extract substrings. Progress is steady. 📈 For those working across different languages, do you prefer stricter typing (like Python) or looser typing (like standard JavaScript) for daily tasks? 👇 #Python #LearningInPublic #SoftwareEngineering #FrontendDev #CodeWithHarry
To view or add a comment, sign in
-
-
Day 17 – Strings, Lists & Practical Logic Building in Python Today’s session was a mix of real-world logic building and deeper practice with strings and lists in Python. I started with a simple electricity bill calculation program using conditional statements. It helped me understand how tier-based logic works in real-life scenarios and how to structure conditions properly using if-elif-else. Strings – More Practice Revised and practiced important string methods: upper() and lower() for case conversion isupper() and islower() for validation capitalize() vs title() replace() with control over number of replacements This reinforced how strings are immutable and how every operation returns a new modified string. Lists – Slicing & Methods in Depth Worked extensively on list operations and understood the difference between modifying and non-modifying methods. Slicing Practice: Normal slicing Step slicing Reverse slicing Skipping elements using step values List Methods Explored: append() → add single element extend() → add multiple elements from iterable insert() → add element at specific index remove() → remove first occurrence pop() → remove by index (returns removed value) clear() → empty the list index() → find position of element sort() → modifies original list sorted() → returns new sorted list reverse() → reverse list order join() → join list elements into a string I also observed: How insert() behaves with negative and out-of-range indexes Difference between sort() and sorted() How extend() works differently with list, tuple, and set Key Takeaways Understanding method behavior is more important than just memorizing syntax Some methods modify the original list, others return new values Real learning happens when testing edge cases Logic building is improving step by step Day 17 was more about strengthening fundamentals and building clarity in how Python handles data structures. #Python #PythonLists #PythonStrings #ProgrammingBasics #DataStructures #CodingPractice #DailyLearning #ProblemSolving #LearnToCode #SoftwareDevelopment
To view or add a comment, sign in
-
Day 3 of 10: Python Control Flow & The Quirks of Iteration 🐍🔁 We are onto Day 3 of my Python sprint! Today’s focus from the CodeWithHarry handbook was all about conditional expressions and loops. Moving my backend logic from Node.js to Python is feeling smoother by the day. The pseudo-code nature of it—dropping the curly braces and relying entirely on clean indentation—makes writing complex logic incredibly fast. Here is what stood out to me today: 📌 Streamlined Conditionals: Trading else if for Python's elif. It’s a small syntax shift, but it makes chained conditional blocks read much cleaner. 📌 The range() Function: Iterating with for i in range() is a brilliantly efficient way to generate sequences and handle iterations compared to the traditional for (let i = 0; i < n; i++) we use in JS. 📌 The for...else Construct: This was today's biggest "Aha!" moment. Python actually allows you to attach an else block directly to a for loop. It only executes if the loop exhausts naturally without hitting a break statement. This is an amazing built-in tool for writing search algorithms without needing extra flag variables! All my practice scripts for today are already pushed to the tasks folder in my GitHub repo. Tomorrow, we get into Functions and Recursion! Python devs: How often do you actually use the for...else construct in your production AI or backend code? Is it a daily driver or a niche trick? Let’s discuss! 👇 #Python #SoftwareEngineering #BackendDevelopment #10DayChallenge #CodeWithHarry
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
That’s a good explanation. However, the actual constructor is __new__, while __init__ is an initializer. The __new__ method runs before the instance is created and is responsible for creating and returning the new object. The __init__ method runs after the instance has been created and is used to initialize its attributes.