【问题标题】:Recursive function calls inside class seem to return multiple 'self' attributes?类内的递归函数调用似乎返回多个“自我”属性?
【发布时间】:2023-04-11 09:32:01
【问题描述】:

我正在尝试创建一段代码,该代码可以以不同的方式打印出链接列表,具体取决于链接列表的调用方式以及您选择从列表中的哪个位置开始。

为此,我选择了一个递归函数,您在初始调用中将数据传递给该函数,它通过递归调用传递该数据和更多数据,以构建所需的输出形式。但是,当我尝试递归调用该函数时,“self”参数似乎发送了两次,将自身写入函数的前两个参数中。

class LinkedList(object):

def __init__(self):
    self.head = Node()
    self.allNodeLocations = {}

def buildLinkedList(self, curNode, finish=99999, between=False, location=[0, 0], allNodeLocations={}, i=0):
    def __init__(self, name):
        self.curNode = curNode
        self.finish = finish
        self.between = between
        self.location = location
        self.allNodeLocations = allNodeLocations
        self.i = i

    if len(curNode.getChildren()) > 1:
            for child in curNode.getChildren():
                location, allNodeLocations, i = self.buildLinkedList(self, child, finish, between, 
                         location, allNodeLocations, i) #THIS IS WHERE THE CODE FAILS
            location[0] -= 1
            i -= 1
    return location, allNodeLocations, i

在上述情况下,'child' 变量应该是一个 Node 对象。运行上面的脚本会给出“TypeError:buildLinkedList() 需要 2 到 7 个位置参数,但给出了 8 个”

如果我改为使用该行调用函数

    self.buildLinkedList(self, child)

并使用pycharm调试器检查值,self和curNode(即子变量)都指向同一个LinkedList对象,函数定义标题'finish'中的下一个变量包含child传递给的节点对象应该在 curNode 变量下输入的函数。

请注意,为了便于阅读,我已删除大量代码,如果需要,其余代码如下。抱歉,目前有大量无用的代码,我打算以后用它做事......

class Node(object):

    def __init__(self, busNum = None, data=None, children=None, parents=None):
        self.busNum = busNum
        self.data = data
        self.children = []
        self.parents = []
        if children:
            self.children += children
        if parents:
            self.parents += parents

    def getChildren(self):
        return self.children

    def getParents(self):
        return self.parents

    def setChild(self, child):
        self.children.append(child)

    def setParent(self, parent):
        self.children.append(parent)

    def getData(self):
        return self.data

    def setData(self, data):
        self.data = data

    def toString(self):
        return "Bus Number: " + str(self.busNum) + ", Data: " + str(self.data)


class LinkedList(object):

    def __init__(self):
        self.head = Node()
        self.allNodeLocations = {}
        # self.curLocation = [0, 0]

    def addBus(self, bus, data, children, parents):
        newNode = Node(bus, data, children, parents)

    def buildLinkedList(self, curNode, finish=99999, between=False, location=[0, 0], allNodeLocations={}, i=0):
        def __init__(self, name):
            self.curNode = curNode
            self.finish = finish
            self.between = between
            self.location = location
            self.allNodeLocations = allNodeLocations
            self.i = i

        allNodeLocations[curNode] = location
        if i >= finish:
            return allNodeLocations

        if len(curNode.getChildren()) == 0:
                # If there are no children, set the location of the current bus, and go down a y level
            # location[0] -= 1
            location[1] += 1
            # i -= 1
            # curNode = prevNode
            return location, allNodeLocations, i
        elif len(curNode.getChildren()) == 1:
                # If there is 1 child, set its location and move onto its next child, once we return from there,
                # subtract 1 from the current iteration and x location
            location[0] =+ 1
            i =+ 1
            if i > finish:
                i -= 1
                return location, allNodeLocations, i
            # prevNode = curNode
            curNode = curNode.getChildren()[0]
            location, allNodeLocations, i = self.buildLinkedList(self, curNode, finish, between, location, allNodeLocations, i)
            location[0] -= 1
            i -= 1
            return location, allNodeLocations, i
        elif len(curNode.getChildren()) > 1:
                i += 1
                location[0] += 1
                for child in curNode.getChildren():
                    location, allNodeLocations, i = self.buildLinkedList(self, child, between=False)#, finish, between, location, allNodeLocations, i)
                location[0] -= 1
                i -= 1
        return allNodeLocations

e=Node(4,11)
f=Node(5,11)
g=Node(6,11)
h=Node(8,11)
j=Node(10,11)
k=Node(11,11)
i=Node(7,33,[h])
d=Node(9,66,[j,k])
c=Node(3,66,[i])
b=Node(2,132,[e,f,g])
a=Node(1,66,[b,c])

listOfNodes = [a,b,c,d,e,f,g,h,i,j,k]

print(d.getChildren())
# d.setChild(11)
# g.setChild(9)
# i.setParent(4)
# print(d.getChildren())

linkd=LinkedList()
linkd.buildLinkedList(a)

--更新-- 用户 Moxy 指出了该问题,解决方法是在 buildLinkedList 调用中删除对 self 的调用。

顺便说一句,当我运行脚本时,它会在每次迭代中创建一个带有“位置”变量的字典,但是,每当位置变量更新时,它都会更新字典中它的所有实例。

为了澄清,我使用“allNodeLocations[curNode] = location”行递归地制作字典,每次递归调用都会更新curNode和location变量,但是当位置发生变化时,它会立即将字典更新为相同字典中每个单元格的值。

有没有办法只获取位置变量的值而不是指针(如果这就是问题所在)?

【问题讨论】:

    标签: python class recursion


    【解决方案1】:

    当您调用 buildLinkedList 时,请删除 self。它表示类的实例,因此您在类中创建函数时添加它,但在调用它时从不添加。如果添加self,它会在buildLinkedList 的参数中创建一个偏移量。

    试试这个:

    self.buildLinkedList(curNode, finish, between, location, allNodeLocations, i)
    

    解决这个问题后,您将拥有一个

    ValueError: too many values to unpack (expected 3)
    

    要修复它,请将 buildLinkedList 的最后一个 return 替换为:

    return None, allNodeLocations, None
    

    --更新--

    这个更新问题是因为列表是通过引用而不是值传递的,修复它试试:

    allNodeLocations[curNode] = location by allNodeLocations[curNode] = list(location)
    

    或

    allNodeLocations[curNode] = location by allNodeLocations[curNode] = location[:]
    

    顺便说一句,我不明白你通过获取位置值而不是指针的意思

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2019-12-08
    • 1970-01-01
    • 2017-12-29
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多