【发布时间】:2025-12-30 21:00:16
【问题描述】:
我有这个 Python 3 伪代码:
def f1():
a, b, c, d, e, f = some_other_fn()
if (condition):
f2(a, b, c, d, e, f)
def f2(a, b, c, d, e, f):
complex_set_of_operations_with(a, b, c, d, e, f)
for i in range(1000):
f(1)
现在,我对f2() 中冗长的签名和重复感到有些恼火,并想将其封装到f1() 中:
def f1():
def f2():
complex_set_of_operations_with(a, b, c, d, e, f)
a, b, c, d, e, f = some_other_fn()
if (condition):
f2()
for i in range(1000):
f(1)
现在,我的问题是:如果我运行 f1() 一千次,解释器是否必须解析 f2() 一千次,或者它是否足够聪明以创建可重用的引用?
【问题讨论】:
-
为什么不
def f2(*args): complex_set_of_operations_with(*args) -
您是递归调用
f2,还是在f1的多个地方调用?如果没有,您可以完全删除f2并将其代码内联到f1。 -
@Chris_Rands:我必须使用
a、b、c、d、e和f在f2()中的不同位置,我找到了明确声明它们更具可读性。 -
@tobias_k 我只在
f1中调用它,这也是我想封装它的原因。我可以内联它,但我喜欢将操作代码与触发它的条件分开。这主要是一个风格和可读性问题——不可否认,还增加了一些学术好奇心。
标签: python performance encapsulation