python - 使用类属性作为函数参数?

标签 python function

所以我在 Python 中有一个有效的排序算法。 (它的确切内容与这个问题无关。)它使用一个名为“people”的列表,其中包含类实例,并且该函数被硬编码为按特定属性“wealth”对该列表进行排序。

def my_sort(seq):
    # sorts by seq[n].wealth
    ...
my_sort(people)

现在,我想概括该函数,以便我可以按任何属性进行排序。

def my_sort2(seq, key):
    # sorts by seq[n].key
    ...
my_sort2(people, wealth)

但这当然会引发错误,因为它不知道将“财富”视为类属性。那么,这怎么可能呢?

最佳答案

您可以传递属性的名称:

def my_sort2(seq, keyname):
    sort by getattr(seq[n], keyname)

my_sort2(people, 'wealth')

或者一个 getter 仿函数:

def my_sort2(seq, keyfunc):
    sort by keyfunc(seq[n])

my_sort2(people, operator.attrgetter('wealth'))

我更喜欢后一种方法,因为它更通用。例如,它很容易允许计算键。

关于python - 使用类属性作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7822249/

相关文章:

python - Optuna 多目标优化的最佳参数

python - Pandas:将索引更改为列

python - 页面源未反射(reflect)通过 selenium 提交表单后的更改

Chapel 中的函数变量和函数数组

javascript - 为什么我的功能只是闪烁并带我返回主页?

jquery - 使用严格导致未定义的函数

function - 名称错误 : global name not defined when calling method inside class

python - 使用主显示器的 Psychopy 脚本

python - 调用 Python 静态方法对象

python - Keras fit_generator 上的错误,多运行了几步