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

时间:2014-06-14 14:22:42

标签: 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, color)color指的是一个整数变量。

2 个答案:

答案 0 :(得分:9)

你有两个问题:

  1. 如果您尝试拨打foo(apple, color),则会收到NameError,因为color未在您拨打foo的范围内定义;和
  2. 如果您尝试拨打foo(apple, 'color'),则会收到AttributeError,因为Fruit.attribute不存在 - 您,此时,实际上使用attribute参数foo
  3. 我认为您要做的是从属性名称的字符串中访问属性,您可以使用getattr

    >>> def foo(obj, attr):
        output = str(getattr(obj, attr))
        print(output)
    
    
    >>> foo(apple, 'color')
    red
    

    请注意,您不应将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
    

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

答案 1 :(得分: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.

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

def foo(object, attribute):
    print(getattr(object, attribute))
.
.
.
foo(apple, 'color')