Python: @staticmethod vs @classmethod (Explained Simply) In Python classes, not all methods behave the same. There are 3 types of methods: 1) Instance Method: Works with object data. def show_name(self): • Uses self. • Accesses instance variables. 2) Class Method (@classmethod): Works with class-level data. @classmethod • Uses cls. • Can modify class variables. • Shared across all objects. 3) Static Method (@staticmethod): Independent utility function. @staticmethod • No self, no cls. • Doesn’t modify class or instance. • Used for helper logic. In this example: • show_name() → works on object. • change_company() → updates company for all employees. • greet() → simple helper function. Think of it like this: - Instance → works with object. - Class → works with class. - Static → works independently. Comment down, Which one do you use most in your code?
Python Static vs Class Methods Explained
More Relevant Posts
-
Python nodes are fine until you need to reason about executor timing. Most ROS2 teams start in Python. It is faster to iterate, the API is cleaner, and rclpy works well for the majority of nodes. Then at some point a callback is late, a timer drifts, a high-frequency publisher starts dropping, and suddenly you are reading the Global Interpeter Lock (GIL) documentation at 11pm. The split that i have usually seen in practice: - Write Python for: launch files (you have no choice), testing with launch_testing, diagnostic scripts, parameter tuning nodes, any node that runs at low frequency and does not touch hardware directly. - Write C++ for: hardware interfaces in ros2_control, any node with timing guarantees, high-frequency publishers above ~50Hz, anything that shares data between callbacks without wanting to think about the GIL, Nav2 and MoveIt plugins. The non-obvious part: it is not really about speed. A Python subscriber at 10Hz is fine. The problem is that Python's executor behavior under load is harder to reason about. A C++ node with a MultiThreadedExecutor and proper callback groups gives you explicit control over what runs concurrently. rclpy gives you the same API but the GIL means your mental model of "these callbacks run in parallel" is not always true. Senior engineers on most teams I know write production logic in C++ and use Python for everything else. Not because they prefer C++. Because the failure modes are easier to find. What is your current split? And has the GIL ever caught you off guard in a ROS2 node? I would love to hear about your experience!
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
-
Some python list tutorials stop at my_list.append(x). That is the surface. Underneath, a list is a C struct called PyListObject holding an array of pointers to PyObject instances. The list does not store your data. It stores references to wherever your data lives on the heap. That single fact is the root cause of the aliasing bugs that catch developers off guard. A few things that land differently once you understand the memory model: Why append() is O(1) amortized. CPython over-allocates on resize using the growth sequence 0, 4, 8, 16, 24, 32, 40, 52, 64, 76... so the O(n) copy cost spreads across many appends. Why b = a and then mutating b also mutates a. They are two names pointing at the same PyListObject. Why list.sort() runs in O(n) on nearly-sorted data. Timsort, written by Tim Peters in 2002, finds already-sorted runs and merges them. Stability has been a documented guarantee since Python 2.2. Why list.pop() from the end is O(1) but list.pop(0) is O(n). Elements after the index have to shift. I put together an 11-tutorial learning path on PythonCodeCrack that walks through lists from first principles through the copy semantics and aliasing patterns that cause hard-to-trace bugs. Fundamentals first (creation, slicing, append vs extend, sorting, comprehensions), then the advanced group (flattening, shallow vs deep copy, why your list keeps changing unexpectedly). https://lnkd.in/g5uUXj6d #Python #SoftwareEngineering #CPython #Programming
To view or add a comment, sign in
-
💡 How Python makes iterables out of indices Objects that implement the dunder method `__getitem__` are automatically iterable, as long as they: - accept integer indices starting at `0`; and - raise an `IndexError` at the end of the sequence. The dunder method `__getitem__` of the class `ArithmeticSequence`, shown in the diagram below, satisfies both constraints. Since it satisfies both constraints, instances of `ArithmeticSequence` are automatically iterable: ```py seq = ArithmeticSequence(5, 3, 6) for value in seq: print(value, end=", ") # 5, 8, 11, 14, 17, 20, ``` Since Python sees the method `__getitem__`, it infers that the looping behaviour must be to go through the container index by index, producing `seq[0]`, `seq[1]`, `seq[2]`, etc. When an `IndexError` is raised, Python stops iterating. Did you know Python could do this?
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
-
🐍 The developer just had to name it python 🐍 Respect ✊ *Guido van Rossum* He was Python’s “Benevolent Dictator For Life” (BDFL) until stepping down in 2018. Now Python’s run by a steering council It could have been given any other name but he just settled for python 🐍 😁😂😂😂😂😂😂😂😂😂😂 The chances of seriously listening to phython code will make you a star in programming, try it. This example uses SMTP (works with Gmail, Outlook, or most mail servers). import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime # Email configuration SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 EMAIL_ADDRESS = "your_email@gmail.com" EMAIL_PASSWORD = "your_app_password" # Recipient TO_EMAIL = "recipient@example.com" def generate_report(): # Replace this with your real report logic today = datetime.now().strftime("%Y-%m-%d") report = f""" Daily Report - {today} - System Status: OK - Users Active: 120 - Errors Logged: 2 Regards, Automated System """ return report def send_email(): report = generate_report() msg = MIMEMultipart() msg["From"] = EMAIL_ADDRESS msg["To"] = TO_EMAIL msg["Subject"] = "Daily Automated Report" msg.attach(MIMEText(report, "plain")) try: server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.starttls() server.login(EMAIL_ADDRESS, EMAIL_PASSWORD) server.send_message(msg) server.quit() print("Email sent successfully!") except Exception as e: print("Error:", e) if __name__ == "__main__": send_email()
To view or add a comment, sign in
-
🚀 #python #Ep 2: Understanding #Data Types in Python In Python, everything is an object, and every object has a data type. Data types define what kind of value a variable holds and what operations you can perform on it. 🔗 Code reference: https://lnkd.in/ei6STRqT 🧠 Why Data Types Matter? Prevent errors in your code Help Python understand how to store and process data Make your programs efficient and readable 📌 Common Python Data Types 🔢 Numeric Types int → Whole numbers (10, -5) float → Decimal numbers (3.14) complex → Complex numbers (2+3j) 📝 String (str) Used to store text Example: "Hello Python" ✅ Boolean (bool) Only two values: True or False 📦 Sequence Types list → Ordered & mutable → [1, 2, 3] tuple → Ordered & immutable → (1, 2, 3) 🗂️ Mapping Type dict → Key-value pairs → {"name": "Hari"} 🔁 Set Types set → Unordered & unique values → {1, 2, 3} 💡 Pro Tip Python is dynamically typed, meaning you don’t need to declare data types explicitly — Python figures it out at runtime 🔍 Example x = 10 # int y = 3.14 # float name = "Hari" # str is_active = True # bool 📣 Final Thought Mastering data types is the foundation of Python programming. Once you understand them, everything else becomes easier! #Python #Coding
To view or add a comment, sign in
-
-
🐍📰 Altair: Declarative Charts With Python Build interactive Python charts the declarative way with Altair. Map data to visual properties and add linked selections. No JavaScript required https://lnkd.in/ghbuFY3H
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
-
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