如何将对象属性的名称传递给函数?例如,我试过:
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
指的是一个整数变量。
答案 0 :(得分:9)
你有两个问题:
foo(apple, color)
,则会收到NameError
,因为color
未在您拨打foo
的范围内定义;和foo(apple, 'color')
,则会收到AttributeError
,因为Fruit.attribute
不存在 - 您不,此时,实际上使用attribute
参数foo
。我认为您要做的是从属性名称的字符串中访问属性,您可以使用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')