Two parent classes. Same method name. One child class. Which one does Python call? I assumed Python would just crash — or at least throw an error. It didn't. It silently picked one. And I had no idea which one or why. ━━━━━━━━━━━━━━━━━━━━━━ This is Multiple Inheritance in Python. class A: ····def hello(self): print("Hello from A") class B: ····def hello(self): print("Hello from B") class C(A, B): ····pass C().hello() ━━━━━━━━━━━━━━━━━━━━━━ Output: Hello from A But why A and not B? Python follows something called MRO — Method Resolution Order. It uses an algorithm called C3 Linearization. The rule is simple: Python reads left to right in the inheritance list, then goes up. C → A → B → object So it finds hello() in A first — and stops there. ━━━━━━━━━━━━━━━━━━━━━━ You can actually see Python's MRO yourself: print(C.mro) Output: ▶ C → A → B → object ━━━━━━━━━━━━━━━━━━━━━━ My Software Engineering brain connected this immediately. In Java, multiple inheritance isn't even allowed for classes — exactly because of this ambiguity. Java forces you to use interfaces instead. Python allows it — but quietly follows a strict order behind the scenes. The lesson: Python is never random. There's always a rule. You just have to find it. ━━━━━━━━━━━━━━━━━━━━━━ Senior developers — has MRO ever caused a bug in your production code that took you a while to trace? Genuinely curious how often this actually bites people. #Python #OOP #DataScience #SoftwareEngineering
Python MRO Explained: Method Resolution Order
More Relevant Posts
-
🚀 Day 14/60 – Dictionary Comprehension (Level Up Your Python 🚀) Yesterday you learned list comprehension. Today, let’s level up 👇 🧠 What is Dictionary Comprehension? A quick way to create dictionaries in one clean line. ❌ Traditional Way numbers = [1, 2, 3, 4] squares = {} for num in numbers: squares[num] = num * num print(squares) ✅ Dictionary Comprehension Way numbers = [1, 2, 3, 4] squares = {num: num * num for num in numbers} print(squares) 👉 Cleaner. Faster. More Pythonic. 🔍 With Condition numbers = [1, 2, 3, 4, 5, 6] even_squares = {num: num * num for num in numbers if num % 2 == 0} print(even_squares) ⚡ Real Example names = ["adeel", "ali", "ahmed"] name_length = {name: len(name) for name in names} print(name_length) ❌ Common Mistake {num * num for num in numbers} # ❌ This creates a set Correct: {num: num * num for num in numbers} # ✅ Dictionary 🔥 Pro Tip Use dictionary comprehension when: ✅ You want clean transformation of data ❌ Avoid if logic becomes too complex 🔥 Challenge for today 👉 Create numbers from 1 to 5 👉 Create dictionary where: Key = number Value = cube of number Comment “DONE” when finished ✅ Follow Adeel Sajjad to stay consistent for 60 days 🚀 #Python #PythonProgramming #LearnPython #Coding #Programming #Developer #SoftwareEngineering
To view or add a comment, sign in
-
-
Do you actually understand what Python is… or do you just know its definition?🐍 Most people say: “Python is a high-level, interpreted language created by Guido van Rossum in 1991.” That’s not understanding. That’s memorization. Python is not just a language. Python is a layer of abstraction. ⚙️ When early languages like C were designed, they stayed very close to the machine. 💻 You had to think about memory, pointers, and low-level details. That’s why C is fast—because it sits close to hardware. But here’s the trade-off: Closer to hardware → more control, more complexity Higher abstraction → less control, more productivity Python was built to move you away from the machine and toward problem-solving. Someone already did the hard work: Memory management? Handled. Complex system interactions? Hidden. Syntax complexity? Reduced. So instead of thinking: “How does the computer execute this?” You think: “What logic solves this problem?” 🚀 That’s why Python is widely used in: Machine Learning Web Development Automation Data Analysis Not because it’s the fastest — it’s not. But, because it allows you to build faster and think more clearly. Final point: 🎯 Python didn’t become popular by accident. It became popular because it removes friction between your idea and implementation. #python #pythonprogramming #learnpython #coding #programming #machinelearning #deeplearning #datascience #artificialintelligence #ai #ml #softwareengineering #systemdesign #computerscience #codinglife #programminglogic
To view or add a comment, sign in
-
-
I used to write extra code for things Python could do in one line. Loops for indexing. Manual swaps for reversing. Temporary variables for pairing data. It worked… but it wasn’t elegant. Then I started really understanding Python lists and its built-in functions — and it honestly felt like upgrading the way I think. The first time I used sort(), I realized I didn’t need to reinvent sorting logic every time. But more importantly, I learned that how you sort matters — like using a custom key instead of forcing the data to fit your logic. reverse() taught me something subtle. There’s a difference between changing the original list and creating a new one. That distinction sounds small, but it matters a lot when you're debugging or working with shared data. Then came zip() — and this one completely changed how I handle multiple lists. Instead of juggling indexes, I could iterate cleanly over related data. It made my code feel more readable, almost like telling a story instead of solving a puzzle. And enumerate()… this replaced so many messy loops. No more manual counters. Just clean, intentional iteration with both index and value. What really stood out to me wasn’t just shorter code — it was clearer thinking. I stopped asking, “How do I write this logic?” And started asking, “What’s the cleanest way Python already supports this?” That shift matters a lot in interviews and real projects. Because good code isn’t just about working — it’s about being readable, maintainable, and efficient. Now when I solve problems, I try to use built-ins wherever it makes sense. Not as shortcuts, but as tools that reflect a deeper understanding of the language. Still learning, still improving — but definitely writing better code than I was yesterday.
To view or add a comment, sign in
-
-
Same condition. Same variables. Different result… depending on how you write it. 🤯 This is where Python stops being “easy” and starts being precise. 🧠 Today’s concept: Truthiness, Short-Circuiting & Operator Precedence Three small ideas. Massive impact. # 1. Truthiness (Not just True/False) data = [] if data: print("Has data") else: print("Empty ❌") 👉 Empty values ([], {}, "", 0, None) are False 👉 Everything else is True # 2. Short-Circuiting (Python stops early) def check(): print("Checking...") return True result = False and check() print(result) 👉 Output: False 👉 check() NEVER runs Because: False and anything → already False Python doesn’t evaluate further # 3. OR short-circuit behavior def fallback(): print("Fallback executed") return "Default" value = "Data" or fallback() print(value) 👉 Output: "Data" 👉 fallback() NEVER runs Because: True or anything → already True # 4. Operator Precedence (Silent bugs ⚠️) a = True b = False c = False result = a or b and c print(result) 👉 Output: True Because Python reads it as: a or (b and c) NOT: (a or b) and c ⚠️ Real-world bug pattern # Looks correct, but isn't if user == "admin" or "manager": print("Access granted") 👉 ALWAYS True ❌ Correct way: if user == "admin" or user == "manager": 💡 Advanced takeaway: and → returns first False or last True value or → returns first True value Conditions don’t always return True/False—they return actual values #Python #AdvancedPython #CodingJourney #LearnInPublic #100DaysOfCode #SoftwareEngineering #Debugging #TechSkills
To view or add a comment, sign in
-
🐍 Lambda Function in Python (Simple Explanation) Lambda is just a **small one-line function**. No name, no long code… just quick work ✅ 👉 Instead of writing this: ```python def add(x, y): return x + y ``` 👉 You can write this: ```python add = lambda x, y: x + y print(add(3, 5)) # 8 ``` 💡 Where do we use it in real life? 🔹 1. Sorting (very useful) ```python students = [("Vinay", 25), ("Rahul", 20)] students.sort(key=lambda x: x[1]) # sort by age print(students) ``` 🔹 2. Filter (get only even numbers) ```python numbers = [1,2,3,4,5,6] even = list(filter(lambda x: x % 2 == 0, numbers)) print(even) # [2,4,6] ``` 🔹 3. Map (change data) ```python numbers = [1,2,3] square = list(map(lambda x: x*x, numbers)) print(square) # [1,4,9] ``` ✅ Use lambda when: • Code is small • Use only once • Want quick solution ❌ Don’t use when: • Code is big or complex 💡 Simple line to remember: “Short work → Lambda” 👉 Are you using lambda or still confused? #Python #Coding #LearnPython #Programming #Developers #PythonTips
To view or add a comment, sign in
-
-
🚀 Lecture 2 is Done! — Teaching Python to Think & Decide Lecture 2 of my Introduction to Python course for MSBA students at SZABIST Islamabad just wrapped up, and this is where things get really interesting! In Lecture 1, we gave Python instructions. In Lecture 2, we taught Python how to make decisions. Here's what we covered: 🔹 Boolean Values Every decision in programming boils down to: True or False? Python's Boolean data type has just these two values. Every financial model that says "if revenue exceeds threshold, then…" is powered by this idea. 🔹 Comparison Operators We learned to let Python compare values: ✅ Equal (==), Not equal (!=) ✅ Greater than (>), Less than (<), and their or-equal variants Key lesson: = assigns a value, == compares two values. Mixing these up is the most common beginner mistake! 🔹 Boolean Operators Real decisions combine multiple conditions — "Approve the loan if credit score > 700 and debt-to-income < 40%." 📌 and — True when both conditions are True 📌 or — True when at least one is True 📌 not — Flips True to False and vice versa 🔹 Blocks & Indentation Python uses indentation to define code blocks — forcing clean, readable code from day one. The colon (:) signals that an indented block is coming next. 🔹 if / elif / else — The Core of Flow Control ✅ if — runs code only when a condition is True ✅ elif — checks another condition when the previous was False ✅ else — catches everything else Python evaluates top to bottom and executes only the first match. Order matters — just like structuring decision logic in risk models. 🔹 From Flowcharts to Code Flow control maps directly onto flowcharts. Diamonds are conditions, rectangles are code blocks. If you can draw a decision flowchart, you can write it in Python. 💡 Key Takeaway: Flow control powers every automated decision in finance — credit scoring, fraud detection, portfolio rebalancing. Python's if statement does what Excel's IF() does, but with far more power and scalability. 📚 Resource: https://lnkd.in/dWM25WeX Stay tuned — Lecture 3 is coming up next! 🐍 #Python #MSBA #BusinessAnalytics #Finance #PythonForFinance #Teaching #SZABIST #DataScience #LearningPython #FlowControl
To view or add a comment, sign in
-
🚨 “Python is slow.” If you’ve ever said this… There’s a 90% chance you don’t understand the GIL. And that misunderstanding is costing you performance. Big time. Let’s break your assumption: You spin up 10 threads. You expect 🚀 10x speed. Reality? 👉 Your CPU is still doing ONE task at a time. Welcome to the truth of Python. 🧠 The villain (or hero?): GIL — Global Interpreter Lock It ensures: 👉 Only ONE thread executes Python bytecode at a time 👉 Even on a multi-core machine So yes… ❌ Threads don’t give true parallelism for CPU-heavy work ❌ More threads ≠ more speed ❌ Sometimes performance actually DROPS 💥 Brutal example: You write multithreading for: Data processing Image transformations Heavy calculations And then… “Why is this still slow?” 😐 Because you solved the wrong problem with the wrong tool. 🧵 Where threads ACTUALLY shine: When your program is mostly waiting: ✅ API calls ✅ Database queries ✅ File I/O 👉 While one thread waits, another runs 👉 That’s where multithreading wins ⚙️ Want REAL power? Use Multiprocessing. ✔ Separate processes ✔ Separate memory ✔ Separate Python interpreters ✔ NO GIL bottleneck 👉 Finally… TRUE parallel execution across CPU cores ⚡ Shift your mindset: Multithreading ≠ speed booster Multiprocessing ≠ overkill 👉 They are tools. Use them correctly. 🔥 The rule elite developers follow: 👉 I/O-bound → Multithreading 👉 CPU-bound → Multiprocessing 💣 Hard truth: Most developers don’t have a performance problem… They have a mental model problem. 💬 Be honest: Did you ever assume threads = parallelism in Python? #Python #GIL #Performance #Multithreading #Multiprocessing #BackendDevelopment #Developers
To view or add a comment, sign in
-
-
I spent 3 hours debugging a RecursionError at 2 AM. Turns out, I had no idea what recursion was actually doing to memory. Here's what changed everything for me 👇 ───────────────────── 🧠 WHAT RECURSION REALLY IS ───────────────────── Most tutorials say: "A function that calls itself." That's true. But incomplete. The real story? Every recursive call pushes a new stack frame into RAM. Local variables. Arguments. Return address. All of it — sitting in memory, waiting. For factorial(5), Python holds 6 frames simultaneously before returning a single value. ───────────────────── ⚠️ THE HIDDEN DANGER ───────────────────── Python's default recursion limit is 1000. Hit it → RecursionError. Ignore it → bloated memory. Each frame costs ~300–400 bytes. 1000 frames = ~400 KB of stack. And unlike Java or Scala, Python has NO tail-call optimization. Even "optimized" tail recursion still creates new frames. ───────────────────── ✅ THE FIX ───────────────────── → Use @lru_cache for overlapping subproblems (fib, DP) → Convert deep recursion to iteration → Use trampolining for functional-style recursion → Raise sys.setrecursionlimit() only when you understand why ───────────────────── 💡 THE MENTAL MODEL ───────────────────── Think of the call stack like a stack of plates. Each call = add a plate. Base case = stop adding. Return = remove plates one by one. You wouldn't stack 10,000 plates. Don't stack 10,000 frames. ───────────────────── Recursion isn't bad. Blind recursion is. Understand the memory. Write better code. ───────────────────── Found this useful? ♻️ Repost to help a developer who's debugging at 2 AM right now. Follow me for daily Python deep-dives that go beyond the surface. #Python #Programming #SoftwareEngineering #CodeQuality #PythonTips #RecursionExplained #LearnPython #Developer
To view or add a comment, sign in
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