对象属性是否可以作为函数参数传递

时间:2014-02-21 05:55:23

标签: python object

我无法在Python中将对象属性作为函数参数传递。

def selector_string(antique, field, variable):

     if antique.field == variable:

        return antique

如果我传入相关变量,上面的函数不起作用。

selector_string(item, 'country', 'SINGAPORE')

>>> Antique instance has no attribute 'field'

我哪里出错了?感谢。

2 个答案:

答案 0 :(得分:4)

您应该使用getattr,就像这样

if getattr(antique, field) == variable:

从文档引用,

  

返回object的named属性的值。名字必须是   串。如果字符串是对象属性之一的名称,   结果是该属性的值。例如, getattr(x,   'foobar')相当于x.foobar。如果命名属性没有   如果提供,则返回default,否则返回AttributeError   提高。

如果该属性不在antique中,并且您想要提供默认值,则可以这样做

if getattr(antique, field, None) == variable:

如果None中没有field的值,则antique是返回的默认值。

如果您想知道对象上是否确实存在该属性,您可以像这样使用hastattr

if hasattr(antique, field):
    if getattr(antique, field) == variable:
        ...
        ...
else:
    print "Attribute '{}' not found in antique".format(field)

答案 1 :(得分:0)

确实可以,但你不能只说antique.field因为程序认为你正在寻找一个名为“field”的字段而不是变量字段的内容 。您可以使用getattr函数解决此问题,该函数接受包含字段名称的字符串,并返回具有该名称的字段的值:

def selector_string(antique, field, variable):

   if antique.getattr(field) == variable:
       return antique