将属性名称传递给Python中的函数

use*_*242 3 python attributes

如何将对象属性的名称传递给函数?例如,我尝试过:

def foo(object, attribute):
    output = str(object.attribute)
    print(output)

class Fruit:
    def __init__(self, color):
        self.color = color

apple = Fruit("red")
foo(apple, color)
Run Code Online (Sandbox Code Playgroud)

但上述方法不起作用,因为Python认为,在中foo(apple, color),color指的是一个单一化的变量.

jon*_*rpe 9

你有两个问题:

  1. 如果你试图打电话foo(apple, color),你得到一个NameError因为color没有在你打电话的范围内定义foo; 和
  2. 如果你试图打电话给foo(apple, 'color')你得到一个AttributeError因为Fruit.attribute不存在 - 那时你就不是实际使用attribute参数了foo.

我想你想要做的是从属性名称的字符串中访问一个属性,你可以使用getattr:

>>> def foo(obj, attr):
    output = str(getattr(obj, attr))
    print(output)


>>> foo(apple, 'color')
red
Run Code Online (Sandbox Code Playgroud)

请注意,不应将其object用作变量名称,因为它会影响内置类型.


作为第2点的演示:

>>> class Test:
    pass

>>> def demo(obj, attr):
    print(attr)
    print(obj.attr)


>>> t = Test()
>>> t.attr = "foo"
>>> t.bar = "baz"
>>> demo(t, "bar")
bar # the value of the argument 'attr'
foo # the value of the 'Test' instance's 'attr' attribute
Run Code Online (Sandbox Code Playgroud)

请注意,两个值都不是"baz".


mha*_*wke 5

用途getattr

>>> print getattr.__doc__
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
Run Code Online (Sandbox Code Playgroud)

在您的情况下,像这样定义foo并将属性作为字符串传递:

def foo(object, attribute):
    print(getattr(object, attribute))
.
.
.
foo(apple, 'color')
Run Code Online (Sandbox Code Playgroud)