【问题标题】:Python: How to build a function that takes multiple objects of the same class as input parameter?Python:如何构建一个将同一类的多个对象作为输入参数的函数?
【发布时间】:2020-12-25 14:55:55
【问题描述】:

我正在使用 python 中的链表。

这是我编写的用于构建链表的两个类:

class node:
    
    def __init__(self, value):
        self.value = value
        self.next = None

class linkedList:
    
    def __init__(self):
        self.head = None

# Two linked lists are being created:
l1 = linkedList() #1st linked list
l1.head = node(1)
new_node1 = node(2)
l1.head.next = new_node1

l2 = linkedList() #2nd linked list
l2.head = node(10)
new_node2 = node(20)
l2.head.next = new_node2

现在,我想在 linkedList 类中构建一个函数,该函数将获取两个链表并对它们执行各种任务,例如:比较、连接链表等。

但主要挑战是我不太确定如何构建一个将同一类的多个对象作为输入参数的函数?

非常感谢您的帮助。

提前致谢!

【问题讨论】:

  • def compare(l1: linkedList, l2:linkedList) -> int: ...
  • 有什么问题?编写一个接受多个参数的函数(从技术上讲,您已经在代码中编写了它)或检查对象的类?

标签: python oop linked-list


【解决方案1】:
class linkedList:
    
    #create function of linkedList class which takes exactly 2 linkedList objects:

    def function(obj1: linkedList, obj2: linkedList):
        pass #do whatever you need to do with those objects

那么你就可以应用这个函数了:

linkedList.function(LL1, LL2)

或者您也可以这样做:

class linkedList:
    
    def function(self, obj: linkedList):
        pass

这会将函数应用于调用它的对象,并将另一个对象作为参数传递:

LL1.function(LL2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2011-03-31
    • 2010-12-10
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多