😊❤️ Todays topic: Topic: Polymorphism in Python: ============= Polymorphism means “one interface, multiple implementations”. In simple terms, the same method name can behave differently depending on the object. Example 1: Same method, different classes class Dog: def sound(self): print("Bark") class Cat: def sound(self): print("Meow") for animal in [Dog(), Cat()]: animal.sound() Output: Bark Meow Explanation: Both classes have the same method name, but different behavior. Example 2: Built-in polymorphism print(len("Hello")) # string print(len([1, 2, 3])) # list Output: 5 3 Explanation: len() works differently for different data types. Example 3: Method overriding class Parent: def show(self): print("Parent") class Child(Parent): def show(self): print("Child") obj = Child() obj.show() Output: Child Key Points: Same method name, different behavior Achieved using method overriding or different classes Improves flexibility and code reuse Interview Insight: Polymorphism allows writing generic and reusable code that works with different object types. Quick Question: Is method overloading supported in Python like Java? #Python #Programming #Coding #InterviewPreparation #Developers
Python Polymorphism: One Interface, Multiple Implementations
More Relevant Posts
-
Level Up Your Python API Design: Mastering / and * Have you ever looked at a Python function signature and wondered what those / and * symbols actually do? While many developers stick to standard arguments, modern Python (3.8+) provides surgical precision over how functions receive data. Understanding this is key to building robust, self-documenting APIs. Check out this "Ultimate Signature" example: def foo(pos1, pos2, /, pos_or_kwd1, pos_or_kwd2='default', *args, kwd_only1, kwd_only2='default', **kwargs): print( f"pos1={pos1}", f"pos2={pos2}", f"kwd_only1={kwd_only1}", # ... and so on ) The Breakdown: Positional-Only (/): Everything to the left of the slash must be passed by position. You cannot call foo(pos1=1). This is perfect for performance and keeping your API flexible for future parameter renaming. Positional-or-Keyword: The "classic" Python parameters that can be passed either way. The Collector (*args): Grabs any extra positional arguments and packs them into a tuple. Keyword-Only: Everything after *args (or a standalone *) must be named explicitly. This prevents "magic number" bugs and makes the intent of the caller crystal clear. The Dictionary (**kwargs): Catches any remaining keyword arguments. Why should you care? Good code isn't just about making it work; it’s about making it hard to use incorrectly. By using these boundaries, you create a strict contract. You force clarity where it’s needed (Keyword-Only) and allow flexibility where it’s not (Positional-Only). Are you using these constraints in your daily development, or do you prefer keeping signatures simple? Let’s discuss below! 👇 #Python #SoftwareEngineering #CleanCode #Backend #ProgrammingTips #Python3 #CodingLife
To view or add a comment, sign in
-
😊❤️ Todays topic: Topic: Multithreading vs Multiprocessing in Python: ================ Both are used to run tasks concurrently, but they work differently. Multithreading: Multiple threads run within the same process. import threading def task(): print("Task running") t1 = threading.Thread(target=task) t1.start() t1.join() Explanation: Threads share the same memory space. Multiprocessing: Multiple processes run independently. from multiprocessing import Process def task(): print("Task running") p1 = Process(target=task) p1.start() p1.join() Explanation: Each process has its own memory space. Key Difference: Multithreading → shared memory Multiprocessing → separate memory Important Concept (GIL): Python has a Global Interpreter Lock (GIL). It allows only one thread to execute Python bytecode at a time So multithreading is not ideal for CPU-heavy tasks When to use: Multithreading → I/O-bound tasks (file, network, API calls) Multiprocessing → CPU-bound tasks (calculations, data processing) Interview Insight: Due to GIL, multiprocessing is preferred for parallel execution in CPU-intensive applications. Quick Question: Why is multithreading not effective for CPU-bound tasks in Python? #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
String multiplication in Python: The operator that isn't doing math Most languages treat * as a numeric operator. Python treats it as a contract: repeat this thing, whatever it is. For strings, that means you can multiply a character or a sequence and get back a longer string. It is operator overloading, and it is more useful than it first appears. The most immediate application is terminal output formatting. When you are printing reports or debugging data to the console, visual separation matters. label = "PROCESS SUMMARY" width = 40 print("=" * width) print(label.center(width)) print("=" * width) print(f"{'Records processed:':<25} {'1,204':>10}") print(f"{'Errors:':<25} {'3':>10}") print("=" * width) The separator line is not hardcoded. It scales with width. Change one variable and the entire layout adjusts. That kind of coupling is what separates output you wrote once from output you have to patch every time a label gets longer. The same pattern applies to building simple progress indicators, padding fixed-width columns, or generating placeholder blocks during prototyping. The principle behind it is the same in every case: one source value, every visual element derived from it. There is also a subtler point here. The fact that * works on strings is not a coincidence or a convenience shortcut. It reflects a broader design principle in Python: operators are interfaces, and types implement them. str.mul is as legitimate as int.mul. Understanding that early changes how you read unfamiliar code later. #Python #PythonMOOC2026 #BackendDevelopment #SoftwareEngineering #LearningInPublic #UniversityOfHelsinki
To view or add a comment, sign in
-
-
Sometimes small Python behaviors end up causing big confusion in production. I faced one such case with shallow copies when handling nested lists and dicts. It looked simple at first but ended up modifying original data silently. Wrote a plain and honest Medium piece about what actually happened and how I fixed it. It is not theory or textbook — just one of those bugs you only understand after you hit it yourself. Friend link below ⬇️ https://lnkd.in/ehYY9zRY #Python #BackendDevelopment #SoftwareEngineering #CodingJourney #TechCommunity #MediumDev #PythonTips #LearningByDebugging
To view or add a comment, sign in
-
🚀Today I explored another important concept in Python — Strings 💻 🔹 What is a String? A string is a sequence of characters used to store text data. Anything written inside quotes (' ' or " ") is considered a string in Python. 🔹 How Strings Work: 1️⃣ Each character has a position (index) 2️⃣ We can access characters using indexing 3️⃣ We can extract parts of a string using slicing 4️⃣ We can modify output using built-in methods 👉 Flow: Text → Access/Manipulate → Output 🔹 Operations I explored: ✔️ Indexing Accessing individual characters using position ✔️ Slicing Extracting a part of the string ✔️ String Methods Using built-in functions like upper(), lower(), replace() 🔹 Example 1: Indexing & Slicing text = "Python" print(text[0]) # P print(text[-1]) # n print(text[0:4]) # Pyth 🔹 Example 2: String Methods msg = "hello world" print(msg.upper()) print(msg.replace("world", "Python")) 🔹 Key Concepts I Learned: ✔️ Indexing (positive & negative) ✔️ Slicing ✔️ Built-in string methods ✔️ Immutability (strings cannot be changed directly) 🔹 Why Strings are Important: 💡 Used in user input 💡 Data processing 💡 Text manipulation in real-world applications 🔹 Real-life understanding: Strings are everywhere — from usernames and passwords to messages and data handling in applications Learning step by step and gaining deeper understanding every day 🚀 #Python #CodingJourney #Strings #Programming
To view or add a comment, sign in
-
-
Multithreading vs Multiprocessing in Python — When to Use What? 👉 Choosing the wrong one can actually make your program slower. 🧠 The Core Difference 🔹 Multithreading Runs multiple threads within the same process Shares memory Best for I/O-bound tasks (waiting time) 🔹 Multiprocessing Runs multiple processes (separate memory) True parallel execution Best for CPU-bound tasks ⚠️ The Catch: GIL (Global Interpreter Lock) Python has a limitation 👉 Only ONE thread executes Python bytecode at a time So even with multiple threads: ❌ CPU-heavy tasks don’t run in parallel ⚙️ Example 🔸 Multithreading (I/O Tasks) import threading def task(): print("Running task") t1 = threading.Thread(target=task) t2 = threading.Thread(target=task) t1.start() t2.start() 🔸 Multiprocessing (CPU Tasks) from multiprocessing import Process def task(): print("Running process") p1 = Process(target=task) p2 = Process(target=task) p1.start() p2.start() 🔥 When to Use What? ✅ Use Multithreading for: API calls File handling Database operations ✅ Use Multiprocessing for: Data processing Image/video processing Machine learning workloads 👉 Threads improve efficiency (waiting time) 👉 Processes improve performance (true parallelism) #Python #Multithreading #Multiprocessing #BackendDevelopment #Performance #SoftwareEngineering
To view or add a comment, sign in
-
Python: Do you want to re-use your code? Don't forget the __name__ trick. How does it work? When a script file is called directly by the interpreter, the __name__ variable is automatically set to "__main__". If the script were imported by another script, the __name__ variable gets temporarily set to the module/called-script name while the script is running. This way, you can run the root function (defined below as "main_function") when calling the script directly, but can skip that part and import the supporting functionality if the script is imported by another script. Code re-use! Python code: def main_function(): """ This is a triple-quoted comment. Everything in between the two sets of triple-quotes is a comment. Even if there are multiple lines. Comments are ignored by the interpreter, for use by the programmer. """ pass # null command; do nothing and continue onto the next line # Do everything and call any other needed functions here. return False # Do something. In this case, return boolean False if __name__ == '__main__': main_function()
To view or add a comment, sign in
-
🧠 Python Concept: TypedDict (Structured Dictionaries) Make dictionaries safer 😎 ❌ Normal Dictionary user = { "name": "Alice", "age": 25 } 👉 No structure 👉 Easy to make mistakes ✅ With TypedDict from typing import TypedDict class User(TypedDict): name: str age: int user: User = { "name": "Alice", "age": 25 } 🧒 Simple Explanation 👉 TypedDict = dictionary with rules 📋 ➡️ Defines expected keys ➡️ Defines data types ➡️ Helps catch errors early 💡 Why This Matters ✔ Better type safety ✔ Cleaner code ✔ Great for large projects ✔ Helps with IDE + static checking ⚡ Bonus Example class User(TypedDict, total=False): name: str age: int 👉 Fields become optional 😎 🧠 Real-World Use ✨ API request/response models ✨ Config files ✨ Data validation layers 🐍 Don’t use random dictionaries 🐍 Define structure #Python #AdvancedPython #CleanCode #SoftwareEngineering #BackendDevelopment #Programming #DeveloperLife
To view or add a comment, sign in
-
-
Python Lists vs Tuples (Mutable vs Immutable) Lists = Mutable (can change) list_1 = ['apple', 'banana', 'orange', 'grape', 'mango'] list_2 = list_1 print(list_1) print(list_2) list_1[0] = 'Watermelon' print(list_1) print(list_2) Output: Both lists change (same reference in memory) --- Tuples = Immutable (cannot change) tuple_1 = ('apple', 'banana', 'orange', 'grape', 'mango') tuple_2 = tuple_1 print(tuple_1) print(tuple_2) # This will cause error tuple_1[0] = 'Watermelon' Error: TypeError: 'tuple' object does not support item assignment Key Insights: List → change allowed Tuple → change not allowed Both allow duplicates Both are ordered #Python
To view or add a comment, sign in
-
Today I learned about lambda functions in Python A lambda is just a small, anonymous one-liner function — no name, no `return`, just pure logic. Basic syntax: ``` lambda arguments: expression ``` Instead of writing: ```python def add(a, b): return a + b ``` You can write: ```python add = lambda a, b: a + b ``` But the real power shows up when you pair it with `map()`, `filter()`, and `sorted()`: ```python # Double every number list(map(lambda x: x * 2, [1, 2, 3, 4])) # → [2, 4, 6, 8] # Keep only even numbers list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])) # → [2, 4] # Sort by second element sorted([(1,3),(2,1),(4,2)], key=lambda x: x[1]) # → [(2, 1), (4, 2), (1, 3)] ``` Key rule I'll remember: Use lambda when the logic is small and used once Avoid it when the logic gets complex — just write a proper `def` Small concept, but it shows up everywhere in Python backend code. #Python #Backend #LearningInPublic #100DaysOfCode #Django
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
Python does not support traditional method overloading like Java. However, similar behavior can be achieved using default arguments or *args.