在Python中将属性名传递给函数

在Python中将属性名传递给函数,python,attributes,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) 但是上述方法不起作用,因为Python认为,在foo(apple

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

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)

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

使用
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.
>>> def foo(obj, attr):
    output = str(getattr(obj, attr))
    print(output)


>>> foo(apple, 'color')
red
在您的例子中,像这样定义foo并将属性作为字符串传递:

def foo(object, attribute):
    print(getattr(object, attribute))
.
.
.
foo(apple, 'color')
你有两个问题:

  • 如果您尝试调用
    foo(apple,color)
    ,您会得到一个
    namererror
    ,因为
    color
    未在您调用
    foo的范围内定义;及
  • 如果你试图调用
    foo(apple,'color')
    你会得到一个
    AttributeError
    ,因为
    Fruit.attribute
    不存在-你是而不是,在这一点上,实际上是在
    foo
    中使用
    attribute
    参数
  • 我认为您要做的是从属性名称的字符串中访问属性,您可以使用
    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.
    
    >>> def foo(obj, attr):
        output = str(getattr(obj, attr))
        print(output)
    
    
    >>> foo(apple, 'color')
    red
    
    请注意,不应将
    对象
    用作变量名,因为它会隐藏内置类型


    作为第2点的证明:

    请注意,这两个值都不是
    “baz”