楼主:
bazoo (surfers'paradise)
2018-05-18 15:50:43※ 引述《chan15 (ChaN)》之铭言:
: # -*- coding: utf-8 -*-
: def run():
: def the_name():
: if not hasattr(the_name, 'name'):
: the_name.name = 'test'
: return the_name.name
: for i in range(3):
: print(the_name())
: run()
: print('')
: run()
: print('')
: run()
: 各位好,我想针对上面的 code 写单元测试
: 主要是想判断第一次执行时还没有 the_name.name
: 执行第一次之后便存在这个 property 因此直接回复 the_name.name
: 本是想用 self.assertFalse(getattr(run.the_name.name))
: 不过显然不能这样用,不知道怎么可以达成需求
简单讲,**不行**
https://stackoverflow.com/questions/13606178/
如果只是回文要来回答不行,大概会被众人围殴吧
原则上,要直接 call inner function,没办法
所以解法就要先设计过,这里我想到三种解法:
Method 1. 预先藏一个变量
In [77]: def a():
...: def b():
...: print("Hello b")
...: a._inner = b
...: b()
...: print("Hello a")
...:
In [78]: a()
Hello b
Hello a
In [79]: a._inner()
Hello b
Method 2. 用 class 定义 function
In [80]: class A(object):
...: def __call__(self):
...: self.b()
...: print("hello a")
...:
...: def b(self):
...: print("hello b")
...:
In [81]: a = A()
In [82]: a()
hello b
hello a
In [83]: a.b()
hello b
Method 3. 重新思考这个 inner function 重要性
可以把这个 function 提升到 global function
(怎么这么久才想到简单明了的解法 ,果然老了)
原 PO 的目的是 unit test
要 unit test 表示有一定的重要性
我会顷向拉到 global function
藏起来的 inner function,我会把它跟外面的 function 看成是一体的
unit test 就只会测试外面的 function
test case 就要想办法去测试到 inner function
番外篇:
当然,如过要硬干,还是有办法把 inner function 抓出来
不过,如果你不是要搞你家的 RD team member 的话,请不要参考一下方法
定义我们的 a function
In [84]: def a():
...: def b():
...: print("Hello b")
...: b()
...: print("Hello a")
...:
In [85]: a()
Hello b
Hello a
来看看他 disassembled 之后会变什么东西:
In [86]: dis.dis(a)
2 0 LOAD_CONST 1 (<code object b at 0x109978c00, file "<ipython-input-84-59fd33a9812d>", line 2>)
2 LOAD_CONST 2 ('a.<locals>.b')
4 MAKE_FUNCTION 0
... 下略 ...
其中的 code object b at 0x109978c00 是我们要的东西
然后 a 有个变量叫做 __code__,透过它,把我们要的东西抓出来
再用 eval 执行它
In [88]: eval(list(dis.get_instructions(a.__code__))[0].argval)
Hello b
成功了,脑细胞也死光光了 ..............