在Python中将属性名称传递给函数
我该如何把一个对象的属性名称传递给一个函数呢?比如,我试过这样:
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 个回答
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')
14
你遇到了两个问题:
- 当你尝试调用
foo(apple, color)
时,会出现NameError
错误,因为在你调用foo
的地方,color
这个东西并没有被定义; - 当你尝试调用
foo(apple, 'color')
时,会出现AttributeError
错误,因为Fruit.attribute
这个东西并不存在——在那时,你其实并没有真正使用foo
的attribute
参数。
我觉得你想做的是通过一个字符串来访问属性的名字,这时候你可以使用 getattr
:
>>> def foo(obj, attr):
output = str(getattr(obj, attr))
print(output)
>>> foo(apple, 'color')
red
注意,不要把 object
用作变量名,因为这会覆盖掉内置的类型。
作为第二个问题的演示:
>>> 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"
。