我不确定您所说的“我不想从 func2 返回它们,因为它会影响 func2 的神圣性”是什么意思,但我假设您的意思是它func
有一个明显的 API,这会破坏该 API。
不过,如果您希望调用者能够使用 of 中的这些值,则必须以某种func2
方式将它们传递出去。以下是一些替代方案:
# Internal function used by func2 and func1
def func2_(value):
list1=[]
list2=[]
value=10
#do some operations based on value
(list3,list4)=func3(value)
return list1, list2, list3, list4
# Real func2 with the desired public API
def func2(value):
list1, list2, _, _ = func2_(value)
return list1, list2
def func1() :
value =20
(list1,list2,list3,list4)= func2_(value)
#func1 _has_ list3 and list4
如果问题是func2
有时调用func3
,有时不调用,但func1
总是需要拥有list3
,list4
无论如何......那么你必须弄清楚如果从不调用func1
应该func3
得到什么值,然后返回那个值。明显的选择是[]
,None
或调用者传入的默认值:
def func2():
list1=[]
list2=[]
value=10
if somePredicate():
(list3,list4)=func3(value)
return list1, list2, list3, list4
else:
return list1, list2, None, None
如果您确定func2
应该始终在调用func3
它时调用它func1
,即使在其他情况下它可能不是,您也需要上面的 wrapper-function 解决方案。
或者,您甚至可以不返回值——没有规则说您的返回值必须始终具有相同数量的组件。这几乎肯定会在将来给您带来可读性问题,但这是完全合法的:
def func2():
list1=[]
list2=[]
value=10
if somePredicate():
(list3,list4)=func3(value)
return list1, list2, list3, list4
else:
return list1, list2
如果调用函数知道什么时候需要 2list
秒和 4 秒,那么你有两个不同的函数,所以你需要包装器。但如果它不可预测,他们可以动态处理它:
lists = function2(value)
if len(lists) == 4:
list1, list2, list3, list4 = lists
# do stuff will all 4 lists
else:
list1, list2 = lists
# do stuff with just 2 lists—or, if you needed the others, complain
或者,如果您有一组数据和一组紧密结合在一起的操作,那么这可能是一个对象的工作:
class Class1(object):
def __init__(self):
self.list1, self.list2, self.list3, self.list4 = [], [], [], []
def func3 (value):
self.list3=[]
self.list4=[]
#do some operations based on value (that presumably modify list3/list4)
def func2(self, value):
self.list1=[]
self.list2=[]
#do some operations based on value (that presumably modify list1/list2)
self.func3(value) # this sets self.list3 and self.list4
def func1(self):
value =20
self.func2(value)
#func1 now has access to the same self.list3 and self.list4 as func2