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

发布于 2024-12-10 12:23:04 字数 391 浏览 3 评论 0原文

所以我有一个可用的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)

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

So I have a working sorting algorithm in Python. (Its exact contents are irrelevant to this question.) It uses a list called 'people' containing class instances, and the function is hard-coded to sort that list by a specific attribute, 'wealth'.

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

Now, I'd like to generalize the function so I could sort by any attribute.

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

But this, of course, throws an error, because it doesn't know to consider 'wealth' as a class attribute. So, how is this possible to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回旧景 2024-12-17 12:23:05

您可以传递属性的名称:

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'))

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

You could pass the name of the attribute:

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

my_sort2(people, 'wealth')

or a getter functor:

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

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

I prefer the latter approach as it is more generic. For example, it easily allows for computed keys.

调妓 2024-12-17 12:23:05

通用属性 getter 函数 getattr 应该可以工作:

gettattr(obj, name)

The generic attribute getter function getattr should work:

gettattr(obj, name)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文