首页 > 解决方案 > 如何在python函数中传递具有属性值的对象

问题描述

我正在进行排序,但我无法以特定方式调用该函数。

基本上,我想要做的是创建一个函数,该函数接受具有属性值的对象节点列表,并返回一个列表,其中原始列表中的项目存储到子列表中。相同值的项目应该在同一个子列表中,并按降序排序。

为了继续代码,我想知道这个参数应该是什么。

def advanced_sort(<What will come here according to the call>):

函数调用:

advanced_sort([Node(1), Node(2), Node(1),Node(2)])

任何人都可以帮我解决代码吗?提前致谢。

标签: pythonpython-3.xfunction

解决方案


advanced_sort接受一个参数:一个列表(或者可能是一个任意的迭代)。因此,签名只有一个参数:

def advanced_sort(nodes):

忽略类型提示,签名不会也不能反映单个参数的内部结构;它只是一个名称,用于引用函数体内传递的值。

在正文中,您可以编写代码,假设nodes是一个列表,并且列表的每个元素都是一个Node实例,因此您可以执行诸如假设每个值作为Value属性的事情。

def advanced_sort(nodes):
    # If nodes is iterable, then x refers to a different
    # element of the iterable each time through the loop.
    for x in nodes:
        # If nodes is a list of Node instances, then
        # x is a Node instance, and thus you can access
        # its Value attribute in the normal fashion.
        print("Found value {}".format(x.Value))

假设Nodelike的定义

class Node:
    def __init__(self, v):
        self.Value = v

的上述定义advanced_sort将产生以下输出:

>>> advanced_sort([Node(3), Node(2), Node(1),Node(2)])
Found value 1
Found value 2
Found value 3
Found value 4

推荐阅读