Python Learning Journey (Day-17) : Constructor (__init__) & Instance Variables in Python Yesterday, we learned about Class and Object. Today, we learn how objects get their initial data and how that data is stored. This is where OOP starts to feel real. ⭐ What is a Constructor? A constructor is a special method in Python that runs automatically when an object is created. In Python, the constructor is named __init__. Its main purpose is to: • Initialize object data • Assign values to variables • Prepare the object for use You don’t call the constructor manually — Python does it for you. ⭐ What are Instance Variables? Instance variables are variables that: • Belong to an object • Store data specific to that object • Are different for each object They are defined inside the constructor using self. Example (conceptually): • One student object has its own name • Another student object has its own name Same class, different data. ⭐ Role of self self represents the current object. It is used to: • Access instance variables • Differentiate object variables from local variables • Allow each object to store its own data Without self, Python cannot know which object the data belongs to. ⭐ How Object Creation Works (Conceptual Flow) Class is defined Object is created Constructor (__init__) runs automatically Instance variables get initialized Object becomes ready to use This happens every time a new object is created. ⭐ Why Constructors Are Important? Constructors ensure that: • Objects start with valid data • No uninitialized variables exist • Code is organized and predictable • Each object has its own identity Almost every real-world class uses a constructor. ⭐ Real-Life Analogy Think of a constructor like: • Filling a form when creating a new account • Entering details when buying a ticket • Setting initial values when registering a user Each user/object has unique data. ⭐ Instance Variables vs Local Variables • Instance Variables Stored inside the object Used throughout the object’s lifetime • Local Variables Exist only inside a method Destroyed after method execution Understanding this avoids confusion later. ⭐Conclusion The constructor (__init__) gives life to objects. Instance variables store the object’s personal data. Together, they make OOP practical and powerful. #Python #Day17 #OOPInPython #Constructor #InstanceVariables #LearnPython #CodingJourney #ProgrammingDaily #TechLearning
Python OOP: Constructors & Instance Variables
More Relevant Posts
-
🔤 Master These Python String Methods & Level Up Your Code 🚀 Strings are everywhere in Python from user input to data processing. If you know these core string methods, your code instantly becomes cleaner, safer, and more professional. ✨ Must-know methods: • split() --> Break a sentence into words for text analysis • strip() --> Clean extra spaces from user input • join() --> Combine list items into a single string • replace() --> Update or sanitize text values • upper() --> Convert text to uppercase for consistency • lower() --> Normalize text for case-insensitive comparison • isalpha() --> Validate name fields (letters only) • isdigit() --> Check if input contains only numbers • startswith() --> Verify prefixes like country codes or URLs • endswith() --> Validate file extensions (.pdf, .jpg, etc.) • find() --> Locate a word or character inside a string 💡 Why they matter? ✔ Clean messy user input ✔ Validate data effortlessly ✔ Write readable, efficient logic ✔ Avoid common bugs in real projects If you’re learning Python , bookmark this 📌 Keep up the 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞 👍 𝐂𝐨𝐧𝐬𝐢𝐬𝐭𝐞𝐧𝐜𝐲 is the 𝐊𝐞𝐲 in 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 💯 👇 Comment “Python” if you want a part-2 with real examples! #Python #PythonProgramming #Coding #LearnToCode #Developer #ProgrammingTips #CleanCode
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 47 / 50..!! TOPIC – List Comprehensions Today I explored one of Python’s most "elegant" features — List Comprehensions. It’s a shorthand way to create new lists based on existing ones, turning 4 lines of code into just 1! 1. The Traditional Way vs. Comprehension Normally, to create a list of squares, you’d need a for loop and .append(). With comprehension, it’s a single line! Python # Traditional Way nums = [1, 2, 3] squares = [] for x in nums: squares.append(x * x) # List Comprehension (The Pythonic Way) squares = [x * x for x in nums] print(squares) # Output: [1, 4, 9] 2. Adding a Condition (The if part) You can filter items while creating the list. Python prices = [10, 55, 80, 25, 100] # Only keep prices over 50 expensive = [p for p in prices if p > 50] print(expensive) # Output: [55, 80, 100] 3. String Manipulation It works perfectly for transforming text data too. Python names = ["srikanth", "python", "dev"] capitalized = [n.capitalize() for n in names] print(capitalized) # Output: ['Srikanth', 'Python', 'Dev'] Why Use List Comprehensions? Readability: Once you learn the syntax, it's much easier to read at a glance. Performance: They are generally faster than standard for-loops for creating lists. Professional: It is a hallmark of "Pythonic" code—showing you really know the language! Mini Task Write a program that: Creates a list of numbers from 1 to 10. Uses List Comprehension to create a new list containing only the even numbers. Prints the resulting list. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 46 / 50..!! TOPIC – Python Modules Today I explored Modules — a way to organize code into separate files and use pre-written code from Python’s massive library. It’s like having a giant toolbox where you only pick the tools you need! 1. Importing Built-in Modules Python comes with many "batteries included" modules. To use them, we simply use the import keyword. Python import math print(math.sqrt(64)) # Output: 8.0 print(math.pi) # Output: 3.14159... 2. Using the random Module Perfect for games or selecting random data. Python import random options = ["Rock", "Paper", "Scissors"] print(random.choice(options)) # Picks a random item print(random.randint(1, 10)) # Random number between 1 and 10 3. Using alias and from You can give a module a nickname or import only a specific part of it to save memory. Python import datetime as dt from math import factorial print(dt.datetime.now()) print(factorial(5)) # Output: 120 Why Use Modules? Efficiency: Don't reinvent the wheel! Use proven code written by experts. Organization: Keep your project files clean by separating logic. Power: Modules allow Python to do everything from web scraping to Data Science and AI. Mini Task Write a program that: Imports the random module. Creates a list called players = ["Alice", "Bob", "Charlie", "David"]. Uses random.choice() to pick a random "Winner" from the list. Prints: "And the winner is... <name>! #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
Day 461: 8/1/2026 Why Python Strings Are Immutable? Python strings cannot be modified after creation. At first glance, this feels restrictive — but immutability is a deliberate design choice with important performance and correctness benefits. Let’s break down why Python does this. ⚙️ 1. Immutability Enables Safe Hashing Strings are commonly used as: --> dictionary keys --> set elements --> For this to work reliably, their hash value must never change. If strings were mutable: --> changing a string would change its hash --> dictionary lookups would break --> internal hash tables would become inconsistent By making strings immutable: --> the hash can be computed once --> cached inside the object --> reused safely for O(1) lookups This is a foundational guarantee for Python’s data structures. 🔐 2. Immutability Makes Strings Thread-Safe Immutable objects: --> cannot be modified --> can be shared freely across threads --> require no locks or synchronization This simplifies Python’s memory model and avoids subtle concurrency bugs. Even in multi-threaded environments, the same string object can be reused safely without defensive copying. 🚀 3. Enables Memory Reuse and Optimizations Because strings never change, Python can: --> reuse string objects internally --> safely share references --> avoid defensive copies Example: --> multiple variables can point to the same string --> no risk that one modification affects another This reduces: --> memory usage --> allocation overhead --> unnecessary copying 🧠 4. Predictable Performance Characteristics Immutability allows Python to store: --> string length --> hash value --> directly inside the object. As a result: --> len(s) is O(1) --> hashing is fast after the first computation --> slicing and iteration don’t need recomputation --> This predictability improves performance across many operations. Stay tuned for more AI insights! 😊 #Python #Programming #Performance #MemoryManagement
To view or add a comment, sign in
-
🐍 Python in 60 Seconds — Day 4 This is where Python starts to feel… easy 😌 In many programming languages, you must declare a variable’s type first. In Python? You just write: x = 10 y = "ten" z = True No declarations. No ceremony. Python figures it out at runtime. 🖨 Printing variables You can print variables directly: message = "Hello, everyone!" print(message) Output: Hello, everyone! You can also print multiple values at once: x = "Hello" y = "Everyone" z = 123 print(x, y, z) Output: Hello Everyone 123 ➡️ Notice how Python automatically adds spaces between values when using print. ⚠️ Beginner trap Using + joins values only if they’re the same type. It also does NOT add spaces automatically. So: "Hello" + "World" ✅ "Hello" + 5 ❌ Use commas in print() when mixing types. 🔄 Variables are flexible You can update a variable — even overwrite it with a different data type: x = 5 x = 6 x = "I love Python" ✅ No errors ✅ Python is just chill Data types (for now) 🔢 Numeric int → 3 float → 3.6 complex → 2 + 3j 📝 Text string → "Python in 60 seconds" (It can hold numbers, but they’re treated as text, not numeric values) ✅ Boolean True or False 🚫 NoneType Written as: None 💡 Insight Python cares more about what the value is now than what it was before. And remember 👇 Consistency beats motivation. See you tomorrow 🚀🐍 #Python #LearnPython #Programming #Coding #TechCareers #DataScience #100DaysOfCode
To view or add a comment, sign in
-
-
Functions in Python: Write Once, Reuse Everywhere Day 8 of #30DaysOfPython 🐍 Until now, we have been writing logic step by step using conditions and loops. Today, we learned how to group that logic into reusable blocks using functions. This is where Python code becomes clean, reusable, and scalable. Example 1: A simple function 👇 def calculate_discount(price): return price * 0.9 final_price = calculate_discount(2500) print(final_price) 👉 Output: 2250.0 Here: 🔹 def → defines a function 🔹 price → input (parameter) 🔹 return → sends the result back Example 2: Reusing the same function 👇 prices = [1500, 2500, 4000] for p in prices: print(calculate_discount(p)) This shows the real power of functions — one logic, multiple values. Example 3: Function with business logic 👇 def sale_type(amount): if amount > 3000: return "High value sale" else: return "Regular sale" print(sale_type(4000)) 👉 Output: High value sale This is how rules and classifications are handled in real projects. DA Insight 💡 Functions help us: ✔ Avoid repeating code ✔ Keep logic in one place ✔ Make code easier to read and maintain ✔ Apply the same rule across datasets Think of it as: Excel → Reusable formulas SQL → Stored logic / expressions Power BI → Measures Python → Functions Next up: Day 9 – Built-in Functions (Python’s shortcuts) 🚀 #30DaysOfPython #PythonForDataAnalysis #DataAnalytics #LearningInPublic #DataAnalyst #Upskilling
To view or add a comment, sign in
-
PYTHON JOURNEY - Day 44 / 50..!! TOPIC – Functions (Basics) Today I explored Functions — the building blocks of reusable code. Instead of writing the same logic over and over, I can now wrap it in a function and call it whenever I need it! 1. Defining a Function We use the def keyword followed by the function name and parentheses. Python def greet(): print("Hello! Welcome to Day 44.") # Calling the function greet() 2. Functions with Parameters You can pass information into a function so it can perform dynamic tasks. Python def welcome_user(name): print(f"Hi {name}, keep up the great coding!") welcome_user("Srikanth") 3. The return Statement Functions can send data back to the main part of the program. Python def add_numbers(a, b): return a + b result = add_numbers(10, 20) print(f"The total is: {result}") Why Use Functions? Reusability: Write once, use everywhere! Organization: Breaks a large, messy program into small, manageable chunks. Testing: It’s much easier to test a small function than a 100-line script. Mini Task Write a program that: Defines a function called calculate_area that takes length and width as parameters. The function should return the area (length * width). Call the function with values 5 and 10 and print the result. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
🚀 Full Stack Journey Day 30: Advanced Python - Destructors & Powerful Object Relationships! 🐍 Day 30 of my #FullStackDevelopment learning series was a deep dive into advanced Python OOP, exploring Destructors for object cleanup and the fundamental concepts of Composition & Aggregation for building strong, flexible object relationships! 🏗️ These topics are crucial for designing scalable and maintainable systems. Today's advanced OOP topics covered: Destructor (__del__) in Python: Explored the __del__ method, Python's destructor. Understood its role in defining cleanup actions that are executed when an object is about to be destroyed (garbage collected). Learned about its non-deterministic nature and when it's appropriate (and not appropriate) to use it for releasing external resources like file handles or network connections. Composition & Aggregation (Object Relationships): Dived into two critical ways objects relate to each other, forming the backbone of complex software architecture: Composition ("has-a" relationship - strong ownership): Mastered composition, where one object owns another. The composed object typically cannot exist independently of the composite object (e.g., a Car has an Engine, and if the car is destroyed, the engine typically is too, in that context). Aggregation ("has-a" relationship - weak ownership): Understood aggregation, where one object has another, but the contained object can exist independently. It represents a "part-of" relationship where parts can be shared (e.g., a Department has Professors, but professors can exist without that specific department). Grasping destructors for resource management and the distinctions between composition and aggregation for object modeling are essential for designing robust, scalable, and well-structured full-stack applications. A huge milestone in your Python OOP journey! 📂 Access my detailed notes here: 👉 GitHub: https://lnkd.in/gYR3QtTi #Python #AdvancedPython #OOP #ObjectOrientedProgramming #Destructor #Composition #Aggregation #ObjectRelationships #FullStackDeveloper #LearningToCode #Programming #TechJourney #SoftwareDevelopment #DailyLearning #CodingChallenge #Day30 LinkedIn Samruddhi P.
To view or add a comment, sign in
-
-
🧠 Python Concept You MUST Know: The Walrus Operator (:=) — Assignment Expressions This feature was added in Python 3.8, but many developers STILL don’t use it. Let’s break it down simply 👇 🧒 Simple Explanation Imagine you’re doing homework ✏️. Normally you must: ✨ Solve the math problem ✨ Then write the answer again somewhere else The walrus operator lets you: ✔ Solve AND store the answer at the same time 🔹 Before Walrus Operator You had to repeat the value: data = input("Name: ") while data != "": print("Hello,", data) data = input("Name: ") The value data appears twice. 🔹 After Walrus Operator (Cleaner) while (data := input("Name: ")) != "": print("Hello,", data) Now the value is: ✔ Read ✔ Stored ✔ Used all in one expression. 🔥 Another Real Example Without walrus: numbers = [1, 2, 3, 4, 5] squares = [n*n for n in numbers if n*n > 10] With walrus: numbers = [1, 2, 3, 4, 5] squares = [sq for n in numbers if (sq := n*n) > 10] ✔ No redundant calculation ✔ More efficient ✔ Cleaner logic 🧠 When Should You Use It? Use walrus when it: ✔ Avoids repeated calculations ✔ Saves variable re-checks ✔ Makes loops simpler ✔ Makes comprehensions cleaner ❌ When Should You Avoid It? Avoid walrus when: ✖ it makes code harder to read ✖ complex expressions become messy Rule: Use it sparingly and only when it improves clarity. 🎯 Interview Gold Line “The walrus operator assigns and returns a value in a single expression, reducing repetition.” Short, clear, senior-level explanation. ✨ One-Line Rule Use := when you need the value immediately and repeatedly. ⭐ Final Thought The walrus operator is one of those features that: ✔️ Cleans up your code ✔️ Improves performance ✔️ Shows deeper Python understanding 📌 Save this post — mastering walrus makes you look like an advanced Python developer. #Python #LearnPython #PythonDeveloper #PythonTips #PythonTricks #Programming #CleanCode #SoftwareEngineering #AssignmentExpressions #TechLearning #DeveloperLife #CodeNewbie
To view or add a comment, sign in
-
-
"Performance tips in Python: vectorization & memory (Part 4)" At small scale, almost any Python code “works.” Once you’re dealing with millions of rows, the difference between a loop and a vectorized operation can mean minutes vs hours. Here’s how I think about performance in real data work: 1️⃣ Stop looping over rows when you don’t have to Row-by-row for loops feel intuitive, but they’re usually the slowest option. Vectorized operations in pandas or NumPy apply logic to entire columns at once, leveraging optimized C under the hood instead of pure Python. 2️⃣ Watch your data types like a hawk Memory issues often come from heavier types than necessary: float64 when float32 is enough, or long strings where categories would work. Downcasting numeric columns and converting repeated text to category can dramatically reduce memory usage and speed up operations. 3️⃣ Process large data in chunks (or scale out) If a dataset doesn’t fit comfortably in memory, reading and processing it in chunks is often better than loading everything at once. At larger scales, pushing transformations to distributed engines (like Spark) lets Python focus on orchestration and specialized logic. 4️⃣ Measure, don’t guess Simple timing and memory checks — timing a cell, inspecting DataFrame. info(), or sampling before and after changes — turn performance from guesswork into an experiment. Over time, this builds intuition about which patterns are “cheap” and which are “expensive.” These habits don’t just make code faster — they make it more reliable when datasets grow or when a proof-of-concept script needs to become a production pipeline. 👉 If you’re working with growing datasets, start by replacing one loop with a vectorized operation and one wide numeric column with a more efficient type. You’ll feel the difference quickly. #Python #Pandas #Performance #DataEngineering #BigData #AnalyticsEngineering
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