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

2024-05-18 23:07:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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)

Tags: 函数in信息for属性defwith本体
2条回答

您可以执行以下操作:

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)

相关问题 更多 >

    热门问题