在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”