Magic methods, also known as dunder (double underscore) methods in Python, are special methods that start and end with double underscores, such as __init__, __str__, __add__, and __len__. These methods allow us to define the behavior of custom objects when they interact with Python's built-in operations and functions. By leveraging magic methods, developers can create classes that behave like built-in types and integrate smoothly with Python's syntax and conventions.
Magic methods are predefined methods in Python with names surrounded by double underscores. These methods are automatically invoked by the Python interpreter in response to specific operations or built-in functions. For example, the __add__ method is invoked when the '+' operator is used, and __len__ is called when len() is used.
The __new__ method is responsible for creating a new instance of a class. It is rarely overridden but is useful in implementing singleton or immutable types.
class Example:
def __new__(cls):
print("Creating instance")
return super().__new__(cls)
The __init__ method initializes the object after it is created. It is commonly used to assign values to object attributes.
class Person:
def __init__(self, name):
self.name = name
Returns a user-friendly string representation of the object, used by print() and str().
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
Returns an official string representation of the object, often used for debugging.
class Book:
def __repr__(self):
return f"Book({self.title!r})"
Defines equality comparison with ==.
class Point:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
Called when the + operator is used.
class Vector:
def __init__(self, x):
self.x = x
def __add__(self, other):
return Vector(self.x + other.x)
Support operations like +=, -= with methods like:
Called when int() is used on the object.
Called when float() is used.
Used in boolean contexts such as if statements.
class Empty:
def __bool__(self):
return False
Returns the length of the object.
class ShoppingCart:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
Allow custom object indexing, assignment, and deletion.
class MyList:
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
These methods make your object iterable.
class Countdown:
def __init__(self, start):
self.n = start
def __iter__(self):
return self
def __next__(self):
if self.n <= 0:
raise StopIteration
self.n -= 1
return self.n
Allow custom setup and teardown using with statements.
class FileOpener:
def __enter__(self):
print("Opening file")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Closing file")
Allows an object to be called like a function.
class Adder:
def __call__(self, x, y):
return x + y
add = Adder()
print(add(3, 5)) # Output: 8
Intercept attribute access and assignment.
class Logger:
def __getattr__(self, name):
return f"Accessing undefined attribute {name}"
Called when an object is about to be destroyed.
class Sample:
def __del__(self):
print("Object is being destroyed")
Used by the in keyword.
class Inventory:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
Defines behavior for reversed().
Used to restrict instance attributes and save memory.
class Student:
__slots__ = ['name', 'age']
Used in custom metaclasses to override isinstance() and issubclass().
Magic methods provide a powerful interface to Python's object model. They allow your classes to behave like built-in types and work seamlessly with Python syntax and built-in functions. From object initialization and representation to operator overloading, iteration, and context management, magic methods unlock Pythonβs full potential for clean, expressive, and elegant object-oriented design.
Understanding and applying these methods effectively can greatly enhance your ability to write flexible, maintainable, and Pythonic code. While magic methods offer a lot of power, they should be used carefully to avoid making the code unnecessarily complex or surprising.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved