如何在Python中从字符串传递位置参数

时间:2018-08-03 00:02:29

标签: python

我花了一些时间弄清楚这一点,因此我发布了此问答。 假设您有一个def my_func(group)函数,该函数带有一个自变量 ,该函数将在下一个函数中用作位置自变量 def set_permission(group_user=None, group_admin=None) 。所以:

group = 'group_user'
my_func(group):
  if group == 'group_user':
    set_permission(group_user='write')
  if group == 'group_admin':
    set_permission(group_admin='write')

但是如果group可以是20个组合怎么办?

还有来自 Django 的更多“真实”案例:

from models import User, Project
import mommy

def create_instance_of_repetable_model(model, model_field):
  if model == User:
    mommy.make(User, user_perm='write')
  if model == Project:
    mommy.make(Project, project_perm='write')
  if model == Project

1 个答案:

答案 0 :(得分:1)

official python docs中发现:

group = 'group_user'
def my_func(group):
  set_permission(**{group: 'write'})  # it works like set_permission(group_user='write')
  print_permission(group)

my_func(group)  #  prints -> 'group_user': 'write'

group = 'group_admin'
my_func(group)  # prints -> 'group_admin': 'write'

和“现实生活”

from models import User, Project
import mommy

def create_instance_of_repetable_model(model, model_field):
  mommy.make(model, **{model_field: 'write'})