在Python 3中使用对象属性作为参数

在Python 3中使用对象属性作为参数,python,python-3.x,parameters,redundancy,Python,Python 3.x,Parameters,Redundancy,我有一个深度优先搜索算法,它从本体中提取信息 我有一个工作函数来获取具有特定属性的所有对象,但是,我基本上需要对不同的属性执行相同的操作 例如,如果我有这两个简化的函数 def a(): for n in nodes: do something with n.property1 def b(): for n in nodes: do something with n.property2 是否有一种方法可以将所需的属性作为参数传入?因此,我最终得

我有一个深度优先搜索算法,它从本体中提取信息

我有一个工作函数来获取具有特定属性的所有对象,但是,我基本上需要对不同的属性执行相同的操作

例如,如果我有这两个简化的函数

def a():
    for n in nodes:
        do something with n.property1

def b():
    for n in nodes:
        do something with n.property2
是否有一种方法可以将所需的属性作为参数传入?因此,我最终得出以下结论:

def a(property):
    for n in nodes:
        do something with n.property

a(property1)
a(property2)

您可以执行以下操作:

def a(property):
   ...
   print(getattr(n, property))
并使用字符串参数调用此方法:

a("property1")
a("property2")

您可以执行以下操作:

def a(property):
   ...
   print(getattr(n, property))
并使用字符串参数调用此方法:

a("property1")
a("property2")
从技术上讲,是的。getattr是一个内置函数,允许您根据对象的名称从对象获取属性。setattr也存在,可用于根据属性名称为对象中的属性赋值

def a(propertyname):  # pass property name as a string
    for n in nodes:
        do something with getattr(n, propertyname)

a('property1')
a('property2')
然而,这通常被认为有点风险,并且最好以一种不需要的方式构造代码。例如,可以使用lambdas来代替:

def a(getter):
    # pass a function that returns the value of the relevant parameter
    for n in nodes:
        do something with getter()

a(lambda n:n.property1)
b(lambda n:n.property2)
从技术上讲,是的。getattr是一个内置函数,允许您根据对象的名称从对象获取属性。setattr也存在,可用于根据属性名称为对象中的属性赋值

def a(propertyname):  # pass property name as a string
    for n in nodes:
        do something with getattr(n, propertyname)

a('property1')
a('property2')
然而,这通常被认为有点风险,并且最好以一种不需要的方式构造代码。例如,可以使用lambdas来代替:

def a(getter):
    # pass a function that returns the value of the relevant parameter
    for n in nodes:
        do something with getter()

a(lambda n:n.property1)
b(lambda n:n.property2)

你能详细解释一下为什么这被认为是有风险的吗?@SeanPayne主要是因为它更容易无意中弄乱对象,例如随意更改传递给它的变量,但也因为静态代码工具比通常的obj.property语法更难理解。不一定是坏的,而且我在答案中这样写是错误的,我会改变这一点,但在使用getattr之前,您应该明确知道自己在做什么,以免导致难以调试的错误。谢谢,这是有道理的。我将使用它,因为在我目前正在进行的项目中,出现此类问题的风险非常低。你能详细说明为什么这被认为是有风险的吗?@SeanPayne主要是因为它更容易无意中弄乱你的对象,例如随意更改传递给它的变量,但也因为静态代码工具比通常的obj.property语法更难理解。不一定是坏的,而且我在答案中这样写是错误的,我会改变这一点,但在使用getattr之前,您应该明确知道自己在做什么,以免导致难以调试的错误。谢谢,这是有道理的。我将使用它,因为在我目前正在进行的项目中,出现此类问题的风险非常低。