10 Practical Python Magic Method Examples for Iteration and Serialization
This article presents ten practical Python examples that demonstrate how magic methods can be used to implement iterable objects, support slicing and indexing, provide length, string and byte representations, and enable JSON, pickle, and XML serialization.
Iteration and serialization are common functionalities in Python; magic methods enable objects to be iterable and convertible between data formats.
Below are ten practical scenarios demonstrating the use of these magic methods.
1. Implement an iterable object using __iter__ and __next__ :
class MyIterable:
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
value = self.data[self.index]
self.index += 1
return value
my_iterable = MyIterable([1, 2, 3])
for item in my_iterable:
print(item)2. Use a generator to implement an iterable object:
class MyIterable:
def __init__(self, data):
self.data = data
def __iter__(self):
for item in self.data:
yield item
my_iterable = MyIterable([1, 2, 3])
for item in my_iterable:
print(item)3. Implement a sequence with index access using __getitem__ :
class MySequence:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
my_sequence = MySequence([1, 2, 3])
print(my_sequence[0]) # 输出: 14. Implement slicing support in a sequence:
class MySequence:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
if isinstance(index, slice):
return self.data[index.start:index.stop:index.step]
else:
return self.data[index]
my_sequence = MySequence([1, 2, 3, 4, 5])
print(my_sequence[1:4]) # 输出: [2, 3, 4]5. Provide sequence length with __len__ :
class MySequence:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
my_sequence = MySequence([1, 2, 3])
print(len(my_sequence)) # 输出: 36. Define a custom string representation using __str__ :
class MyClass:
def __str__(self):
return "This is MyClass"
obj = MyClass()
print(obj) # 输出: This is MyClass7. Define a custom bytes representation using __bytes__ :
class MyClass:
def __bytes__(self):
return b"MyClass"
obj = MyClass()
print(bytes(obj)) # 输出: b'MyClass'8. Implement JSON serialization with a custom __json__ method:
import json
class MyClass:
def __init__(self, data):
self.data = data
def __json__(self):
return {"data": self.data}
obj = MyClass([1, 2, 3])
json_str = json.dumps(obj, default=lambda o: o.__json__())
print(json_str) # 输出: {"data": [1, 2, 3]}9. Implement pickle serialization using __getstate__ and __setstate__ :
import pickle
class MyClass:
def __init__(self, data):
self.data = data
def __getstate__(self):
return {"data": self.data}
def __setstate__(self, state):
self.data = state["data"]
obj = MyClass([1, 2, 3])
pickle_str = pickle.dumps(obj)
new_obj = pickle.loads(pickle_str)
print(new_obj.data) # 输出: [1, 2, 3]10. Implement XML serialization with a custom __xml__ method:
import xml.etree.ElementTree as ET
class MyClass:
def __init__(self, data):
self.data = data
def __xml__(self):
root = ET.Element("MyClass")
data_element = ET.SubElement(root, "data")
data_element.text = str(self.data)
return root
obj = MyClass([1, 2, 3])
xml_str = ET.tostring(obj.__xml__())
print(xml_str) # 输出:
[1, 2, 3]These examples illustrate common applications of iteration and serialization magic methods, helping you customize object behavior for both iteration and various serialization formats.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.