🧙♂️ Magic Methods in Python (Dunder Methods) Python is known for its powerful and flexible object-oriented features. One of the most interesting concepts in Python is Magic Methods, also called Dunder Methods (Double Underscore Methods). Magic methods allow developers to define how objects behave with built-in operations such as addition, printing, comparison, and more. These methods always start and end with double underscores (__). Example: __init__ __str__ __add__ __len__ They are automatically called by Python when certain operations are performed. --- 🔹 Why Magic Methods are Important? Magic methods help to: ✔ Customize the behavior of objects ✔ Make classes behave like built-in types ✔ Improve code readability ✔ Implement operator overloading They allow developers to write clean, powerful, and Pythonic code. --- 🔹 Commonly Used Magic Methods 1️⃣ __init__ – Constructor This method is automatically called when an object is created. class Student: def __init__(self, name): self.name = name s = Student("Vamshi") --- 2️⃣ __str__ – String Representation Defines what should be displayed when we print the object. class Student: def __init__(self, name): self.name = name def __str__(self): return f"Student name is {self.name}" s = Student("Vamshi") print(s) --- 3️⃣ __len__ – Length of Object Allows objects to work with the len() function. class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) t = Team(["A", "B", "C"]) print(len(t)) 4️⃣ __add__ – Operator Overloading Defines how the + operator works for objects. class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value n1 = Number(10) n2 = Number(20) print(n1 + n2) 🔹 Key Takeaway Magic methods make Python classes more powerful and flexible by allowing objects to interact naturally with Python's built-in operations. Understanding magic methods helps developers write cleaner and more advanced object-oriented programs. #Python #PythonProgramming #MagicMethods #DunderMethods #OOP #Coding #LearnPython #SoftwareDevelopment
Python Magic Methods: Customizing Object Behavior with Dunder Methods
More Relevant Posts
-
🚀 Day 3 – Python Practice Progress( 6 of 50 questions solved) Problems I practiced today: ✔ Check if a number is even or odd ✔ Find the largest of three numbers ✔ Print numbers from 1 to N ✔ Find the sum of numbers from 1 to N ✔ Check if a number is prime ✔ Check if a string is a palindrome While solving these, I practiced using: • Conditional statements • Loops (while / for) • Input validation using try–except • String slicing (for palindrome checking) 💡 One interesting concept I explored today was Python slicing: s = "python" print(s[::-1]) This reverses the string because the step -1 makes Python traverse the sequence backwards. Small problems like these are helping me build stronger problem-solving skills in Python. Looking forward to practicing more tomorrow. #Python #DataScience #Programming 1 Check if a number is even or odd. try: num1=int(input("Enter a Number : ")) if num1%2==0: print("number is even") else: print("number is odd") except ValueError: print("invalid input. Please enter a number") 2. Find the largest of three numbers. try: num1=int(input("Enter first Number: ")) num2=int(input("Enter second Number: ")) num3=int(input("Enter third Number: ")) if num1>num2 and num2>num3: print("Larget Number is :", num1) elif num2>num3 and num2>num1: print("Largest Number is :", num2) else: print("Largest Number is :", num3) except ValueError: print("invalid Input. Please enter a number") 3 Print numbers from 1 to N try: num1=int(input("Enter a Number: ")) if num1>0: s=0 while s<=num1: print(s) s=s+1; else: p=0 while p>=num1: print(p) p=p-1; except ValueError: print("invalid input, please enter a number") 4 Find the sum of numbers from 1 to N. try: num=int(input("Enter a number : ")) if num>0: s=0 i=0 while i<=num: s=s+i; i=i+1; print(s) else: p=0 q=0 while q >=num: p=p+q; q=q-1; print(p) except ValueError: print("invalid input. Enter correct Number") Check if a number is prime. try: num=int(input("Enter a number : ")) if num>1: is_prime=True i=2 while i <num: if num%i==0: is_prime=False break i=i+1 if is_prime: print("Number is prime") else: print("Number is not prime") else: print("Enter a number greater than 1") except ValueError: print("Invalid Input. enter valid number") 6. Check if a string is a palindrome. try: num=str(input("Enter a sring:")) if num==num[::-1]: print("Palindrome") else: print("not a palindrome") except ValueError: print("invalid input. Enter a string")
To view or add a comment, sign in
-
🧠 Python doesn’t “free memory”. It negotiates with it. Most developers know that Python has Garbage Collection. Very few know how it actually works internally. Let’s break it down. 1. Reference Counting (Primary Memory Manager) At the core of Python’s memory management is reference counting. Every object in Python maintains a counter that tracks how many references point to it. Example: a = [1,2,3] b = a Now the list object has 2 references. Internally (in CPython): PyObject ├── ob_refcnt ← reference count └── ob_type Whenever a new reference is created → refcnt +1 Whenever a reference is deleted → refcnt -1 When the count hits 0, Python immediately deallocates the object. That’s why: a = [1,2,3] del a Memory is freed instantly. ⚡ This makes Python’s memory management very fast and deterministic. But there is a problem. 2. The Circular Reference Problem Reference counting cannot detect cycles. Example: a = [] b = [] a.append(b) b.append(a) Even if you delete both: del a del b Both objects still reference each other. So their reference count never reaches 0. Memory leak. This is where Python’s Garbage Collector comes in. 3. Generational Garbage Collector Python adds a cycle detector on top of reference counting. It uses a generational model. Objects are divided into 3 generations: Generation 0 → New objects Generation 1 → Survived one GC cycle Generation 2 → Long lived objects Why? Because most objects die young. This is called the Generational Hypothesis. So Python runs GC more frequently on young objects. Example thresholds: Gen0 threshold ≈ 700 allocations Gen1 threshold ≈ 10 Gen0 collections Gen2 threshold ≈ 10 Gen1 collections This keeps GC fast and efficient. 4. How Cycle Detection Works Internally Python uses a mark-and-sweep style algorithm. Steps: 1️⃣ Identify container objects (lists, dicts, classes) 2️⃣ Track references between them 3️⃣ Temporarily reduce reference counts 4️⃣ Objects that reach zero → unreachable cycle 5️⃣ Free them All of this is implemented in: Modules/gcmodule.c Inside CPython. 5. Interesting Internals You can actually inspect GC behavior: import gc gc.get_threshold() gc.get_count() gc.collect() You can even disable GC: gc.disable() Which some high-frequency trading systems and low latency apps do to avoid GC pauses. (Manual control > unpredictable pauses) 6. Why Python Rarely Leaks Memory Because it combines: ✔ Reference counting (instant cleanup) ✔ Generational GC (cycle detection) This hybrid model makes Python one of the most predictable memory managers among dynamic languages. Most developers use Python. Very few explore CPython internals. But once you understand things like: • PyObject • reference counters • generational GC You start seeing Python less like a language… and more like a beautifully engineered runtime system. #Python #CPython #GarbageCollection #Programming #PythonInternals #SoftwareEngineering
To view or add a comment, sign in
-
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
To view or add a comment, sign in
-
🐍 30 Python Challenges to Test Your Skills! 💻 1️⃣ Reverse a string without using loops 🔄 2️⃣ Count duplicates in a list 📝 3️⃣ Flatten a nested list 📂 4️⃣ Find all prime numbers up to N 🔢 5️⃣ Check if a string is a palindrome 🔁 6️⃣ Swap two variables in Python ⚡ 7️⃣ Merge two dictionaries efficiently 🗂️ 8️⃣ Remove all vowels from a string ✂️ 9️⃣ Sort a list of dictionaries by a key 🔑 🔟 Generate Fibonacci numbers in one line 🔢 1️⃣1️⃣ Find the most common element in a list 📊 1️⃣2️⃣ Remove duplicates while preserving order ✅ 1️⃣3️⃣ Find largest & smallest number without min()/max() 🔝🔽 1️⃣4️⃣ Count character occurrences in a string 🔡 1️⃣5️⃣ Reverse words in a sentence 🔁 1️⃣6️⃣ Check if two strings are anagrams 🔤 1️⃣7️⃣ Check if a number is a perfect square ◼️ 1️⃣8️⃣ Transpose a 2D list (matrix) 🔄 1️⃣9️⃣ Convert a list of strings to integers, ignoring invalid inputs 🔢 2️⃣0️⃣ Filter even numbers from a list ✨ 2️⃣1️⃣ Calculate factorial using recursion or loops 🔁 2️⃣2️⃣ Check if a number is prime efficiently 🔢 2️⃣3️⃣ Generate all subsets of a list 📂 2️⃣4️⃣ Capitalize the first letter of each word ✍️ 2️⃣5️⃣ Merge two sorted lists into one sorted list 🗂️ 2️⃣6️⃣ Find second largest number in a list 🔝 2️⃣7️⃣ Count vowels in a string 🔡 2️⃣8️⃣ Check if a list is sorted ✅ 2️⃣9️⃣ Find indices of all occurrences of an element 📌 3️⃣0️⃣ Check if a string is a pangram 🔠 💡 Pro Tip: The most Pythonic solutions often use list comprehensions, sets, dictionaries, and built-in functions. ⚡ Try them out and comment your favorite solution! Don’t forget to share tips & tricks you use daily in Python. 🔁 Repost to help others learn faster ❤️ Like if you found it useful 📥 Save it for future reference 👥 Tag someone who needs this! #Python 🐍 #Programming 💻 #CodingChallenge 🚀 #Developers 👨💻 #TechInnovation 💡 #AI 🤖 #MachineLearning 🧠 #DataScience 📊 #Automation ⚡#SoftwareEngineering 💻 #ProgrammingLife 📝 #TechTrends 📈 #PythonTips 🐍 #LearnToCode 📚 #ProblemSolving 🧩 #DeveloperCommunity #TechSkills ⚡ #PythonProgramming 🐍
To view or add a comment, sign in
-
🐍 3 Python Built-ins That Look Simple… But Are More Powerful Than They Seem One thing I appreciate about Python is how some of the most useful tools look deceptively simple. At first glance, they seem basic. But once you understand the one feature that really matters, they become incredibly practical in real projects. Here are 3 built-ins that quietly make Python code cleaner and more expressive. 🔢 1. sorted() — More Than Just Sorting Numbers Most people think sorted() is mainly for sorting numbers or strings. But the real power comes from key=. In real applications, you're rarely sorting plain numbers. Instead, you're sorting things like: 👤 Users 📋 Tasks 📁 Files 📦 Dictionaries The key parameter tells Python which part of each item should determine the order. Examples in real projects: ✔️ Sort users by age ✔️ Sort tasks by priority ✔️ Sort files by modification date Instead of restructuring your data or writing extra logic, sorted() lets you clearly express how your data should be ordered. 🔗 2. zip() — Pair Related Data Cleanly A very common pattern looks like this: names[i] ages[i] It works… but it also means manually managing indexes. zip() removes that extra work. It lets you iterate through related values together, without worrying about positions. Example scenarios: 👤 Names + ages 🛒 Products + prices 📅 Dates + sales numbers Another benefit: if the lists have different lengths, zip() automatically stops at the shortest one. The result? ✔️ Less indexing ✔️ Cleaner loops ✔️ Easier-to-read code 🔁 3. enumerate() — When You Need Index + Value You’ve probably seen this pattern before: for i in range(len(items)): It works, but it’s not the cleanest approach. enumerate() already gives you both the index and the value in one step. This makes loops much more natural. Common use cases include: 📋 Printing numbered lists 📊 Tracking item positions 🧭 Working with ordered data A small change—but it often makes loops simpler and clearer. 💡 The Bigger Lesson Many Python built-ins are like this. They look simple at first, so people only use them at a surface level. But once you understand the feature that really matters, your code becomes: ✔️ clearer ✔️ shorter ✔️ easier to reason about And that’s a pretty good trade. 💬 Which Python built-in improved your code the most once you truly understood it? #Python #Programming #SoftwareEngineering #PythonTips #CleanCode #DeveloperProductivity #CodingTips
To view or add a comment, sign in
-
-
1: Everything is an object? In the world of Python, (an integer, a string, a list , or even a function) are all treated as an objects. This is what makes Python so flexible but introduces specific behaviors regarding memory management and data integrity that must be will known for each developer. 2: ID and type: Every object has 3 components: identity, type, and value. - Identity: The object's address in memory, it can be retrieved by using id() function. - Type: Defines what the object can do and what values could be hold. *a = [1, 2, 3] print(id(a)) print(type(a)) 3: Mutable Objects: Contents can be changed after they're created without changing their identity. E.x. lists, dictionaries, sets, and byte arrays. *l1 = [1, 2, 3] l2 = l1 l1.append(4) print(l2) 4: Immutable Objects: Once it is created, it can't be changed. If you try to modify it, Python create new object with a new identity. This includes integers, floats, strings, tuples, frozensets, and bytes. *s1 = "Holberton" s2 = s1 s1 = s1 + "school" print(s2) 5: why it matters? and how Python treats objects? The distinction between them dictates how Python manages memory. Python uses integer interning (pre-allocating small integers between -5 and 256) and string interning for performance. However, it is matter because aliasing (two variables pointing to the same object) can lead to bugs. Understanding this allows you to choose the right data structure. 6: Passing Arguments to Functions: "Call by Assignment." is a mechanism used by Python. When you pass an argument to a function, Python passes the reference to the object. - Mutable: If you pass a list to a function and modify it inside, the change persists outside because the function operated on the original memory address. - Immutable: If you pass a string and modify it inside, the function creates a local copy, leaving the original external variable untouched. *def increment(n, l): n += 1 l.append(1) val = 10 my_list = [10] increment(val, my_list) print(val) print(my_list) *: Indicates an examples. I didn't involve the output, you can try it!
To view or add a comment, sign in
-
-
📘 Book review: Time Series Analysis with Python Cookbook This time, we explored Time Series Analysis with Python Cookbook by Tarek Atwan, and it was a strong reminder that good forecasting starts with good thinking. What we liked 👇 ⏱️ Time series as a way of thinking It understands change over time - the patterns, drivers, and uncertainties behind the data. 🧹 Real-world analytics, not theory Built around practical problems using Python, reflecting how analysts actually work with messy, imperfect datasets in industry. 📚 Cookbook style that works Easy to dip into specific topics like seasonality, missing data, decomposition, forecasting, and model evaluation. ⚖️ Discipline over shortcuts Emphasises context, assumptions, visualisation, and validation; not just applying models and hoping for the best. 🔍 Balanced approach to modelling Combines classical and modern techniques without overcomplicating + recognises that simpler, interpretable models are often more useful in practice. Bottom line 💡 Time series analysis isn’t just about forecasting - it’s about understanding systems, asking better questions, and making decisions you can stand behind. Time Series Analysis with Python Cookbook, published by Packt, is a practical and thoughtful resource for analysts working in real-world environments, especially in healthcare and the public sector, where rigour and accountability matter most. You can get it on Amazon: https://amzn.eu/d/0eHhSy6x
To view or add a comment, sign in
-
-
🐍 Python Practice day 5– Here are some problems I solved today: ✅ Find the frequency of elements in a list ✅ Convert a list into a tuple ✅ Find common elements between two sets ✅ Remove duplicates from a list using a set ✅ Find union and intersection of two sets ✅ Create a dictionary from two lists (keys and values) ✅ Count frequency of characters in a string using a dictionary ✅ Merge two dictionaries ----------------------------------Day ----------------- Find the frequency of elements in a list. try: list1=[1,11,1,22,11,1,33,4,5,66,77,66,4,5] frequency_count={} for i in list1: if i in frequency_count: frequency_count[i]=frequency_count[i]+1 else: frequency_count[i]=1 print(frequency_count) except ValueError: print("Error occured") ==Tuples, Sets, Dictionaries == Convert a list into a tuple. list1=[1,2,3,4] tuple1=tuple(list1) print(tuple1) Find common elements between two sets. set1={1,2,3,3,4,4} set2={1,2,4,7} print(set1.intersection(set2)) Remove duplicates from a list using set. list1=[11,11,1,1,1,1,2,3,3] set1=set(list1) print(set1) list1=[11,11,1,1,1,1,2,3,3] unique_list=[] for i in list1: if i not in unique_list: unique_list.append(i) print(unique_list) Find union and intersection of two sets. set1={1,2,3,4,} set2={4,5,6,7,1} union1=set1.union(set2) inter_sec=set1.intersection(set2) print(union1) print(inter_sec) Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1={} for i in range(len(keys1)): dict_1[keys1[i]]=values1[i] print(dict_1) # Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1=dict(zip(keys1,values1)) print(dict_1) Count frequency of characters in a string using dictionary. str1="DpkWtmVMwwids.MMpAMLPlz" dict1={} for i in str1: if i in dict1: dict1[i]=dict1[i]+1 else: dict1[i]=1 print(dict1) # Merge two dictionaries. dict1={"Name":"Deepak", "Subject":"DataScience" } dict2={ "Designation":"DataEngineer", "Salary":"Ye batein btayi ni jati" } dict1.update(dict2) print(dict1) Working through these problems again helped reinforce concepts like: • Iteration and loops • Dictionary operations • Set theory in Python • Clean and Pythonic approaches like zip() and built-in methods #Python #Learning #Programming #DataScienceJourney #CodingPractice
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