__init__(self, ...)
and __str__(self)
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
person = Person("Alice", 30)
print(person) # Output: Alice, 30 years old
__del__(self)
:
class MyClass:
def __del__(self):
print("The object is being deleted.")
obj = MyClass()
del obj # Output: The object is being deleted.
__add__(self, other)
:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Output: (4, 6)
__getitem__(self, key)
:
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
my_list = MyList([1, 2, 3, 4, 5])
print(my_list[2]) # Output: 3
__setitem__(self, key, value)
and __delitem__(self, key)
:
class MyList:
def __init__(self, data):
self.data = data
def __setitem__(self, index, value):
self.data[index] = value
def __delitem__(self, index):
del self.data[index]
def __str__(self):
return str(self.data)
my_list = MyList([1, 2, 3])
my_list[1] = 5
print(my_list) # Output: [1, 5, 3]
del my_list[2]
print(my_list) # Output: [1, 5]
__len__(self)
and __contains__(self, item)
:
class CustomList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __contains__(self, item):
return item in self.data
custom_list = CustomList([1, 2, 3, 4, 5])
print(len(custom_list)) # Output: 5
print(3 in custom_list) # Output: True
print(6 in custom_list) # Output: False
__enter__(self)
and __exit__(self, exc_type, exc_value, traceback)
:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager("example.txt", "w") as f:
f.write("Hello, world!")
__bool__(self)
:
class NonEmptyList:
def __init__(self, data):
self.data = data
def __bool__(self):
return len(self.data) > 0
empty_list = NonEmptyList([])
non_empty_list = NonEmptyList([1, 2, 3])
if empty_list:
print("Empty list is not empty.")
else:
print("Empty list is empty.")
if non_empty_list:
print("Non-empty list is not empty.")
else:
print("Non-empty list is empty.")
__setattr__(self, name, value)
and __getattr__(self, name)
:
class DynamicAttributes:
def __init__(self):
self._data = {}
def __setattr__(self, name, value):
self._data[name] = value
def __getattr__(self, name):
if name in self._data:
return self._data[name]
raise AttributeError(f"'DynamicAttributes' object has no attribute '{name}'")
obj = DynamicAttributes()
obj.attribute1 = 42
print(obj.attribute1) # Output: 42
print(obj.attribute2) # Raises AttributeError: 'DynamicAttributes' object has no attribute 'attribute2'