Practical Examples of Python Iteration and Serialization Magic Methods
This article presents ten practical Python code examples demonstrating how to implement iteration and serialization magic methods, covering iterable objects, generators, indexed and sliced sequences, length, string and byte representations, as well as JSON, pickle, and XML serialization techniques.
Iteration and serialization are common features in Python; magic methods enable objects to be iterable and convertible between data formats.
1. Implementing an iterable object:
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. Using 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. Implementing a sequence with index access:
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. Implementing a sequence with slice access:
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. Implementing length for a sequence:
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. Providing a string representation for an object:
class MyClass:
def __str__(self):
return "This is MyClass"
obj = MyClass()
print(obj) # 输出: This is MyClass7. Providing a bytes representation for an object:
class MyClass:
def __bytes__(self):
return b"MyClass"
obj = MyClass()
print(bytes(obj)) # 输出: b'MyClass'8. Implementing JSON serialization for an object:
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. Implementing pickle serialization for an object:
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. Implementing XML serialization for an object:
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 use cases for iteration and serialization magic methods, helping you customize object behavior for 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.