我希望在一个函数中去掉每个参数中的空白,这个函数需要一串所需的字符串。我不想使用**kwargs,因为它违背了所需参数的目的。
def func(a, b, c):
for argument, argument_value in sorted(list(locals().items())):
print(argument, ':', argument_value)
argument_value = ' '.join(argument_value.split())
print(argument, ':', argument_value)
print('a is now:', a)
func(a=' a test 1 ', b=' b test 2 ', c='c test 3')输出
a : a test 1
a : a test 1
b : b test 2
b : b test 2
c : c test 3
c : c test 3
a is now: a test 1 原“a”参数的期望输出:
a is now : a test 1 作为一个新手,我把这个拼凑在一起,然后,读了python文档,其中清楚地写着。
局部变量() 更新并返回表示当前本地符号表的字典。在函数块中调用空闲变量时,局部变量()会返回,但在类块中不返回。 备注 不应修改本词典的内容;更改可能不会影响解释器使用的局部变量和空闲变量的值。
我在这里尝试的正确方法是什么?
发布于 2015-03-14 03:23:59
您可以使用装潢工来完成这种任务。
其想法是掩盖装饰器后面的实际函数,它将接受泛型参数,对它们进行修改(实际上创建包含修改的新变量),并将修改后的参数传递给真正的函数。
def strip_blanks(f):
def decorated_func(*args, **kwargs):
# Strip blanks from non-keyword arguments
new_args = [ " ".join(arg.split()) for arg in args]
# Strip blanks from keyword arguments
new_kwargs = { key:" ".join(arg.split()) for key,arg in kwargs.items()}
# Pass the modified arguments to the decorated function
# And forward its result in case needed
return f(*new_args, **new_kwargs)
return decorated_func
@strip_blanks
def func(a, b, c):
for i in a, b, c:
print(i)那你就能得到
>>> func(a = " foo bar", b = "baz boz", c = "biz buz ")
foo bar
baz boz
biz buz
>>> func(" foo bar", "baz boz", "biz buz ")
foo bar
baz boz
biz buz
>>> func(a = " foo bar", b = "baz boz", c = "biz buz ", d = " ha ha")
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
func(a = " foo bar", b = "baz boz", c = "biz buz ", d = " ha ha")
File "<pyshell#35>", line 5, in decorated_func
f(*new_args, **new_kwargs)
TypeError: func() got an unexpected keyword argument 'd'
>>> 发布于 2015-03-14 02:41:45
首先,我将您的定义更改为def func(**kwargs)。这需要您提供的任何关键字参数并将它们添加到字典中。例如:
def func(**kwargs):
for key in kwargs:
print key, kwargs[key]
>>> func(a='hello', b='goodbye')
a hello
b goodbye
>>> func()
>>>正如您所看到的,它也不带参数(不需要打印)。从这里开始,查看string方法strip。
编辑:
你给了一些相当武断的限制。所以,你想要的是:
我认为最快的方法是用locals()来做你想做的事情。我猜你在犹豫的是字典的内容没有被修改。这里不需要考虑这一点,因为您正在遍历表示本地字典中的键和值的元组列表。当您执行for argument, argument_value in ____时,您将解压元组并为其中的每个名称分配一个值。然后,当您执行argument_value = 'blahblah'时,您将向argument_value分配一个新字符串。字符串是不可变的,因此您不能更改“放置”的值。您没有更改字典中的值,因为您没有为字典的键分配任何内容。
https://stackoverflow.com/questions/29044824
复制相似问题