You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 level instance variable keeps track of nested depth. Starting at -1 ensures the top-level with block sets the level to 0 (no indentation for the first print).
  • Context Manager Methods:
    • __enter__: Increments the level every time a with block is entered, and returns the instance itself to allow nested use of the same indent object.
    • __exit__: Decrements the level when exiting a with block, reverting to the previous indentation depth.
  • Print Method: Prepends 3 * level spaces 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:17:45