🐍 What is Polymorphism in Python? Most people hear this term and think it’s complex… But it’s actually one of the most powerful and practical concepts in OOP. 💡 Simple Meaning 👉 Polymorphism = “Many Forms” . It means: ➡️ The same method or function can behave differently depending on the object ⚙️ How It Works in Python In Python, polymorphism is mainly achieved using: ✔ Method Overriding (Runtime Polymorphism) ✔ Duck Typing (Python’s flexible behavior) ✔ Operator Overloading (like + working with different types) . 🧠 Real Example Imagine this: Dog 🐶 → “Woof” Cat 🐱 → “Meow” Both use the same method: speak() 👉 But output is different based on the object . 💻 Code Example 𝒄𝒍𝒂𝒔𝒔 𝑨𝒏𝒊𝒎𝒂𝒍: 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒑𝒂𝒔𝒔 𝒄𝒍𝒂𝒔𝒔 𝑫𝒐𝒈(𝑨𝒏𝒊𝒎𝒂𝒍): 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒓𝒆𝒕𝒖𝒓𝒏 "𝑾𝒐𝒐𝒇" 𝒄𝒍𝒂𝒔𝒔 𝑪𝒂𝒕(𝑨𝒏𝒊𝒎𝒂𝒍): 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒓𝒆𝒕𝒖𝒓𝒏 "𝑴𝒆𝒐𝒘" 𝒂𝒏𝒊𝒎𝒂𝒍𝒔 = [𝑫𝒐𝒈(), 𝑪𝒂𝒕()] 𝒇𝒐𝒓 𝒂𝒏𝒊𝒎𝒂𝒍 𝒊𝒏 𝒂𝒏𝒊𝒎𝒂𝒍𝒔: 𝒑𝒓𝒊𝒏𝒕(𝒂𝒏𝒊𝒎𝒂𝒍.𝒔𝒑𝒆𝒂𝒌()) . 👉 Same method → different behavior 🔥 Why It’s Important ✔ Improves code reusability ✔ Makes code flexible & scalable ✔ Reduces complexity ✔ Helps write clean OOP design . ⚠️ Important Note 👉 Python focuses more on method overriding, not traditional overloading like Java . 🎯 Interview Gold Answer “Polymorphism in Python refers to the ability of a method or function to take multiple forms. It allows the same method name to behave differently based on the object, commonly achieved through method overriding and duck typing.” . 💬 Engagement 👉 Can you think of a real-world example of polymorphism? Comment below 👇 . 👉 Comment “PYTHON” if you want more interview questions like this 🚀 . . #Python #PythonProgramming #OOP #Polymorphism #CodingInterview #LearnPython #Developers #SoftwareEngineering #Programming #TechCareers #InterviewPreparation #100DaysOfCode #CodeNewbie
Polymorphism in Python: Many Forms, One Method
More Relevant Posts
-
Python: 05 🐍 Python Iterables: Diving Deeper 🚀 We'll work on different complex types (range, list etc.) and strings iteration. We've already known the for loops, now let's dive into deeper and know what is range function returns. 🔍 We will use a built in 'type' function to get the type of an object. 🛠️ For example: type(5) .. it will return <class 'int'>; that means number 5 is an integer value 🔢 type(range(5)) .. it will return <class 'range'>; that means we get the value from a range function that means its an object of type range! 🧊 Primitive vs. Complex Types 💡 In python we have primitive types like numbers, strings, Booleans. We also have so many complex types, 'range' is one of those complex types. So interesting concept of range is, it is iterable which means we can iterate over it or use it in a for loop. That is why we can write code like this: for x in range(3): Here x can hold number in the range in each iteration. 🔄 Result: 1 2 3 Strings are also iterable! 🧵 For example: for x in "python": print(x) It will return: ✨ p ✨ y ✨ t ✨ h ✨ o ✨ n Which means x will hold one character from the string in each iteration. 🔡 List Iteration 📋: for x in [1, 2, 3, 4,..,n]: print(x) It will return: 1 2 3 4 ... ... ... nth X will hold one object from the list in each iteration. 🎯 #PythonProgramming #PythonDeveloper #Coding #python #iterator #DataScience #pythondeveloper #programmer
To view or add a comment, sign in
-
-
🐍 Python For Loops (Iteration) 🔄 For loops are used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. They let you execute a block of code repeatedly for each item. 👉 They are essential for automating tasks and processing collections of data efficiently. 🔹 1. What is a For Loop? A for loop executes a set of statements, once for each item in a collection. Example: for character in "Python": print(character) Output: P y t h o n 🔹 2. Looping Through a List This is one of the most common uses: going through each item in a list. Syntax: for item in list_name: # code to execute for each item Example: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}.") Output: I like apple. I like banana. I like cherry. 🔹 3. The range() Function The range() function generates a sequence of numbers, often used to loop a specific number of times. • range(stop): Numbers from 0 up to (but not including) stop. • range(start, stop): Numbers from start up to (not including) stop. • range(start, stop, step): Numbers from start up to stop, increasing by step. Example: for i in range(3): # Loop 3 times (0, 1, 2) print(f"Iteration {i}") Output: Iteration 0 Iteration 1 Iteration 2 🔹 4. break and continue Statements • break: Stops the loop completely, even if the iterable hasn't finished. • continue: Skips the rest of the current iteration and moves to the next. Example (break): for number in range(1, 6): if number == 4: break # Stop when number is 4 print(number) Output: 1 2 3 Example (continue): for item in ["A", "B", "C", "D"]: if item == "C": continue # Skip 'C' print(item) Output: A B D 🎯 Today's Goal(What you should do) ✔️ Understand what for loops are ✔️ Iterate over lists, strings, and ranges (using your Python editor) ✔️ Use break and continue to control loop flow (using your Python editor)
To view or add a comment, sign in
-
Assalam o Alaikum 👋 💡 Python Tip: Stop Writing Extra Code — Use "enumerate()"! If you’re learning Python, this small function can make your code cleaner and smarter 🚀 What is "enumerate()"? "enumerate()" is a built-in Python function that helps you loop through a list while keeping track of the index (position) of each item. 👉 Normally, you do this: You create a counter variable, update it manually, and then access elements. But with "enumerate()"… Python does it for you automatically Example: my_list = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(my_list): print(index, fruit) Output: 0 apple 1 banana 2 cherry Why use "enumerate()"? No need to create a separate counter Cleaner & more readable code Less chance of mistakes Perfect for loops where position matters Pro Tip: You can even change the starting index! for index, fruit in enumerate(my_list, start=1): print(index, fruit) 👉 Now counting starts from 1 instead of 0 🚀 Real Use Cases: • Numbering items in a list • Working with indexed data • Tracking positions in loops • Displaying ordered results If you're learning Python, mastering small functions like this will level up your coding fast! 👉 Follow for more simple Python & AI tips #Python #PythonTips #CodingForBeginners #LearnPython #AIAutomation #TechLearning
To view or add a comment, sign in
-
-
Python functions with fixed signatures break the moment you need to forward arguments across abstraction boundaries. *args and **kwargs solve that — and this python tutorial goes well past the syntax. — How CPython actually handles variadic calls at the C level (PyTupleObject, PyDictObject, and why there's a real allocation cost) — Why a defaulted parameter before *args is effectively unreachable via positional calling — and the idiomatic fix — The difference between *args isolating the mapping vs sharing mutable values inside it — ParamSpec (PEP 612) for preserving decorator signatures through the type system — TypedDict + Unpack (PEP 692, Python 3.12) for per-key precision on **kwargs — inspect.Parameter.kind for reading variadic signatures at runtime — the foundation of FastAPI and pytest's dispatch logic — Lambda variadic syntax, functools.wraps, kwargs.setdefault patterns, and common SyntaxErrors caught at parse time Includes interactive quizzes, spot-the-bug challenges, a design decision review, and a 15-question final exam with a downloadable certificate of completion. Full guide: https://lnkd.in/gHkdvCn5 #Python #PythonProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
Habemus smooth in python! For those not familiar with it, smooth is an implementation of Single Source of Error (SSOE) time series forecasting models (ETS, ARIMA and many more) by Ivan Svetunkov. I first came across the package while I was checking the benchmarks for the M5 competition (https://lnkd.in/eKYD7hMG) and then also at work where it was the preferred forecasting package for an old yet durable project. Contrary to most forecasting libraries that prioritise ease of use, smooth prioritises flexibility and control, making it possible to take full advantage of the models capabilities. Needless to say, I like it! Smooth was developed in R, with a lot of C++ code doing the heavy lifting. Within the forecasting community, "smooth in python" became the equivalent of "play Freebird!" (looking at you Nicolas Vandeput). So at some point three to four years ago I texted Ivan and told him that I'll help him port it to python. With the typical confidence that comes with ignorance, I thought it would be a piece of cake! After sorting out all the plumbing between C++ and python, we hit a big wall, tens of thousands of complex R code that had to be translated into python. Luckily we had an ace up our sleeve, Filotas Theodosiou. While most programmers, including me, were arguing about the effectiveness of coding with AI, Filotas was already ahead of the curve and was using his great powers to demolish that wall. Turns out you need all the AI help you can get to produce a fraction of the output of a young Ivan, up in Lancaster doing his PhD. Long story short, a few years later, we have the first python release of smooth on pypi (https://lnkd.in/eKmztdih). We still have a lot of work to do to get to full feature parity with the R version, but we're getting there. For more details and some benchmarks, check the post on Ivan's blog -> https://lnkd.in/ePDy9G8F PS: Special thanks to Ralph Urlus for developing and maintaining CARMA (https://lnkd.in/eMx3d7ns) which was a drop-in replacement for RcppArmadillo and made the whole thing possible!
To view or add a comment, sign in
-
-
How My Python Brain Almost Broke My Rust Code🐍🦀 "I typed return, added a semicolon, and Rust looked at me like I’d just tried to put ketchup on a five-star steak." Coming from Python, we’re treated to a world where functions are like polite requests: "Please do this, and return this value when you're done." It’s explicit. It’s comfortable. It’s what we know. But then I met Rust. I tried to write a simple area function and my Python instincts screamed: “Declare the variables! Use the keyword! End the line!” The result? A syntax error that felt like a personal intervention. ## Under the Hood: The "Semicolon" Secret 🤐 In Python, almost everything is a statement. A statement is a command—it does something. In Rust, the magic lies in Expressions. With a semicolon (;): You’ve created a Statement. It performs an action, returns "unit" (), and effectively "kills" the value's journey. Without a semicolon: You’ve created an Expression. The value is "live," and because it’s the last thing in the block, Rust "yields" it upward to the function caller. You may ask? Why does Rust hate my return 🤷? It doesn't! You can use return, but idiomatic Rust treats the last expression as the "final result" of the block. Think of a Python function as a vending machine (you have to press a button to get the result out). Think of a Rust function as a waterfall (the value naturally flows out the bottom unless you put a dam—a semicolon—in its way). I wanna spoil your evening dear python Devs who are transitioning 🤣: 1. Stop declaring "Return variables": You don't need result = x * y. Just let x * y be the last line. 2. The Semicolon is a Wall: If you want a value to leave a function, don't block it with a ;. 3. Types are Friends: While Python guesses what you’re returning, Rust demands you sign a contract by declaring the return type before you even type the type the logic 🫣 eg.(-> i32) . It feels strict and very manual, but it’s actually Rust’s way of promising your code won't crash at 3 AM 😂. Conclusion: Transitioning from Python to Rust isn't just about learning new syntax; it’s about moving from a "Command" mindset to a "Flow" mindset. Python tells the computer what to do; Rust describes how data should transform brick by brick. Ditch the semicolon, ditch the indentation,embrace the expression, and let your code flow! 🦀✨ #RustLang #Python #CodingHumor #SoftwareEngineering #LearnInPublic
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
-
You might want to take a look at this, Everybody says NumPy is faster than Python List. But, How fast ?? Well I looked into it !! So, here is the overhead of every value you use in Python. Let's say you use a value 42. Here is the detailed overhead. ob_refcnt - 8 bytes (For garbage collection, if reference count is zero, then python just deletes it from RAM) ob_type - 8 bytes (For storing what datatype that value belongs to, here that's integer) ob_digit - 8 bytes (For the actual value - 42). Therefore, 24 bytes for each value. Let's take it a step further. Say you have a 4 values to store just [1, 2, 3, 4] and Let's compare Python list vs NumPy array. Python List : Stores Pointers not the actual values and Hence, you need a list of pointers first, each pointer in the "pointer list" points to the actual value that is scattered across different locations of RAM. So, in-order to store 4 elements. 4 x 8 = 32 (pointer list) 4 x 24 = 96 (actual values) Therefore, 32 + 96 = 128 Bytes. NumPy arrays : It's contiguous and also homogeneous. Also, we don't have pointers model. Here we store actual values next to each other. Thus, giving us a easy traversal using strides. 4 x 8 = 32 Bytes. NumPy can store raw values directly because it enforces a single dtype. Since every element is the same size, it can locate any element using simple math (base + index × itemsize) instead of pointers. Python lists allow mixed types and that's exactly what forces the pointer model. Note: I am only comparing the storage models here. Both Python lists and NumPy arrays have their own object overhead which I've intentionally left out to keep the comparison clean. Apart from storage models. There is another reason why NumPy is so powerful in numerical computations and that is vectorization Vectorization in NumPy : When you do np.sum(a), NumPy runs optimized C code across the entire array in one shot no Python interpreter involved. A Python loop hits interpreter overhead on every single element. That's the real reason NumPy can be 10-100x faster for numerical operations. There is reason why this guy is named as "Numerical Python" !!
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
-
-
Build a RAG pipeline from scratch in Python without LangChain Learn to build a RAG pipeline in Python from scratch using ChromaDB and OpenAI embeddings — no LangChain required. Read the full post 👇 https://lnkd.in/gBHKATvy #GenerativeAI #AI #WebDevelopment #PHP #Python #Developer #LLM
To view or add a comment, sign in
More from this author
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