Python按变量命名关键字

时间:2014-03-10 09:30:29

标签: python python-3.x

我是python的新手,我正在试图弄清楚我是否可以通过字符串传递命名关键字而无需显式调用它们。 这是一个例子:

def test(height, weight):
    print("h=" + str(height))
    print("w=" + str(weight))

test(weight=1, height=2) # output

a = "weight"
b = "height"

test(a=1, b=2) # same output

这可能吗? 谢谢!

3 个答案:

答案 0 :(得分:3)

使用dict

kwargs = {a: 1, b: 2}
test(**kwargs)

答案 1 :(得分:1)

排序。试试这个:

a = "weight"
b = "height"

kwargs = {
    a: 1,
    b: 2
}

test(**kwargs)

答案 2 :(得分:0)

我认为其他答案都没有提到。当然,他们是你提出的问题的正确答案,但他们不是你正在寻找的答案。

我会稍微压缩你的代码:

def test(a):
    print(a)

test("hello, world!")  # Works!. The string is passed to the first paramater, which
                       # is 'a'.

test(a = "hello, world!")  # Works! The 'a' parameter that the function accepts is
                           # set to "hello, world".

test(b = "hello, world!")  # Fails. 'b' does not exist as a parameter in test().

b = "a"  # You're trying to set the 'b' keyword to equal the 'a' keyword here.
         # This does NOT work, which we'll see in a bit.

test(b = "Hello, world!")  # Still fails. The function checks whether 'b' exists 
                           # as a parameter. There is no such parameter.

print(b)  # Prints "a". The variable 'b' was NOT changed when test() was called.
          # You merely tried to change the parameter 'b' of the function test(),
          # which did not exist in the first place.