使用类属性作为函数参数?
所以我有一个可用的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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以传递属性的名称:
或 getter 函子:
我更喜欢后一种方法,因为它更通用。例如,它很容易允许计算键。
You could pass the name of the attribute:
or a getter functor:
I prefer the latter approach as it is more generic. For example, it easily allows for computed keys.
通用属性 getter 函数
getattr
应该可以工作:The generic attribute getter function
getattr
should work: