我并不完全喜欢Tobias 的回答,因为当我org-edit-special
( C-c '
) 一个代码块时,我的 python 模式缓冲区会对我大喊大叫(我有几个带有语法检查器的 python 次要模式),因为带有独立方法的块的意外缩进(因为使用org-src-preserve-indentation
set,我会在我的所有方法前面在它们的各个块中缩进)。因此,我喜欢使用 org-mode 的:noweb标头参数的解决方案:
#+BEGIN_SRC python :tangle "sample.py" :noweb yes
class Test:
<<init_method>> # these are indented
<<more_methods>> # these are indented
#+END_SRC
#+BEGIN_SRC python :noweb-ref init_method
def __init__(self):
self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :noweb-ref more_methods
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))
#+END_SRC
只要您<< >>
在类定义中缩进 Noweb 语法引用(双精度),其他块(“init_method”和“more_methods”)就会与您的缩进纠缠在一起。因此,最终输出的“sample.py”文件如下所示:
class Test:
def __init__(self):
self.a = 'a test class'
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))
好的!