如何用Context Manager实现支持嵌套的Indenter类以生成指定缩进输出?
Solution: Indenter Context Manager
To implement the nested indentation behavior you need, create a context manager that tracks the current indentation level—increasing it when entering a with block and decreasing it when exiting. Here's the working code:
class Indenter: def __init__(self): self.level = -1 # Start at -1 so first enter sets level to 0 def __enter__(self): self.level += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): self.level -= 1 def print(self, text): print(' ' * self.level + text)
How It Works:
- Indentation Tracking: The
levelinstance variable keeps track of nested depth. Starting at-1ensures the top-levelwithblock sets the level to0(no indentation for the first print). - Context Manager Methods:
__enter__: Increments the level every time awithblock is entered, and returns the instance itself to allow nested use of the sameindentobject.__exit__: Decrements the level when exiting awithblock, reverting to the previous indentation depth.
- Print Method: Prepends
3 * levelspaces to the input text, creating the nested indentation effect matching your desired output.
Test Output:
Running your provided code with this Indenter class will produce:
Hi Talk is Cheap! Show me the Code... Torvalds
内容的提问来源于stack exchange,提问作者Mohammad Ali Soltan Hosseini
相关产品推荐
相关产品推荐

