在Org-mode中使用Python类遇问题,附示例代码求助
我来帮你解决在Org-mode里用Python类时遇到的问题~
首先你的测试代码里itm._...是不完整的语法,这会直接导致运行报错。如果你的目标是查看实例的属性或可用方法,我们可以调整代码来实现,同时我也会梳理Org-mode中Python会话的注意事项,帮你顺畅运行代码。
1. 补全并修正测试代码
下面是完整可运行的测试代码块,包含查看实例属性、调用类方法,以及查看对象所有可用属性/方法的示例:
#+BEGIN_SRC python :session :exports both :results output
itm = The_class(3)
print('value of itm.a: {0}'.format(itm.a))
print('add_me result: {0}'.format(itm.add_me()))
print('sqr_me result: {0}'.format(itm.sqr_me()))
print('all attributes & methods: {0}'.format(dir(itm)))
print('custom instance attributes: {0}'.format(itm.dict))
#+END_SRC
2. Org-mode Python会话的关键注意事项
- 先执行类定义代码块:你需要先运行定义
The_class的代码块,再运行测试代码块——因为:session参数启用了会话保持,只有先执行类定义,后续测试代码才能找到这个类。 - 保持会话一致性:如果后续新增代码块,要确保
:session参数和之前的一致(或者都不指定,使用默认会话),这样才能访问到之前定义的类和实例。 - 清理缓存会话:如果遇到奇怪的未定义类/实例问题,可以重启Org-mode的Python会话(比如关闭当前会话后重新执行所有代码块)。
运行修正后的测试代码块后,你应该能得到类似这样的输出:
value of itm.a: 3
add_me result: 6
sqr_me result: 9
all attributes & methods: ['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'a', 'add_me', 'sqr_me']
custom instance attributes: {'a': 3}
内容的提问来源于stack exchange,提问作者Cy Bu

