函数调用的参数传递方式有哪几种 python_如何通过多个函数传递多个参数

假设我们有一个公开的函数(0级)。我们用各种参数来调用这个函数。在内部,此函数调用第二个函数(级别1),但除了调用第三个函数(级别2)作为参数外,不使用任何给定参数。不过,它可能会做一些其他的事情。在

我的问题是。如何在中间层函数(级别1)中传递参数而不产生太多噪音?我在下面列出了一些可能的方法。但要注意的是,其中有些相当丑陋,只是出于完整性的原因。我在寻找一些既定的指导方针,而不是个人对这个问题的看法# Transport all of them individually down the road.

# This is the most obvious way. However the amount of parameter increases the

# noise in A_1 since they are only passed along

def A_0(msg, term_print):

A_1(msg, term_print)

def A_1(msg, term_print):

A_2(msg, term_print)

def A_2(msg, term_print):

print(msg, end=term_print)

# Create parameter object (in this case dict) and pass it down.

# Reduces the amount of parameters. However when only reading the source of B1

# it is impossible to determine what par is

def B_0(msg, term_print):

B_1({'msg': msg, 'end': term_print})

def B_1(par):

B_2(par)

def B_2(par):

print(par['msg'], end=par['end'])

# Use global variables. We all know the pitfalls of global variables. However

# in python there are at least limited to their module

def C_0(msg, term_print):

global MSG, TERM_PRINT

MSG = msg

TERM_PRINT = term_print

C_1()

def C_1():

C_2()

def C_2():

print(MSG, end=TERM_PRINT)

# Use the fact that python creates function objects. We can now append those

# objects. This makes some more 'localised' variables than shown before. However

# this also makes the code harder to maintain. When we change D_2 we have to alter

# D_0 as well even though it never directly calls it

def D_0(msg, term_print):

D_2.msg = msg

D_2.term_print = term_print

D_1()

def D_1():

D_2()

def D_2():

print(D_2.msg, end=D_2.term_print)

# Create a class with the functions E_1, E_2 to enclose the variables.

class E(dict):

def E_1(self):

self.E_2()

def E_2(self):

print(self['msg'], end=self['end'])

def E_0(msg, term_print):

E([('msg', msg), ('end', term_print)]).E_1()

# Create a nested scope. This make it very hard to read the function. Furthermore

# F_1 cannot be called directly from outside (without abusing the construct)

def F_0(msg, term_print):

def F_1():

F_2()

def F_2():

print(msg, end=term_print)

F_1()

A_0('What', ' ')

B_0('is', ' ')

C_0('the', ' ')

D_0('best', ' ')

E_0('way', '')

F_0('?', '\n')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值