【问题标题】:Using an object property as a parameter in Python 3在 Python 3 中使用对象属性作为参数
【发布时间】:2020-07-21 04:10:15
【问题描述】:

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

我有一个工作函数来获取具有特定属性的所有对象,但是,我基本上需要为不同的属性做同样的事情。

如果我有这两个简化的功能,例如

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)

【问题讨论】:

    标签: python python-3.x parameters redundancy


    【解决方案1】:

    从技术上讲,是的。 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 语法。不一定 bad (我的回答是错误的,我会改变它),但在使用 getattr() 之前你一定要知道你在做什么,以免导致错误很难调试。
    • 谢谢,这很有道理。我会使用它,因为在我目前正在进行的项目中出现这类问题的风险非常低。
    【解决方案2】:

    您可以执行以下操作:

    def a(property):
       ...
       print(getattr(n, property))
    

    并使用字符串参数调用此方法:

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

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多