簡體   English   中英

如何修改參數以在Python中正常運行?

[英]How to modify argument to function cleanly in Python?

我有以下代碼,用於遞歸地修改傳遞給函數的節點(該節點包裝在數組中,以便在函數返回后該修改得以持久):

有沒有更好或更干凈的方法來修改參數?

`

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

    def __repr__(self):
        return "node({0})".format(self._value)


    @property
    def next(self):
        return self._next



def foo(a, b):
    if b == 0:
        print "setting to next node",
        a[0] = a[0].next
        print a
        return

    print a
    foo(a, b-1)
    print a

n = node(5, node(8))
foo([n], 2)

`

回答了以下問題: 如何通過引用傳遞變量?

因為您正在操作的參數是對象。 您可以使用__dict__更改對象的整個屬性。 等效於更改項目的每個屬性。 您可以嘗試以下代碼:

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

    def __repr__(self):
        return "node({0})".format(self._value)


    @property
    def next(self):
        return self._next



def foo(a):
    print "setting to next node\n",
    a.__dict__ = getattr(a.next, '__dict__', None)
    return

n = node(5, node(8, node(7)))

print n._value, '->' ,n._next._value
foo(n)
print n._value, '->' ,n._next._value

希望這可以對您有所幫助。

要修改某些東西,該東西必須是可變的。 您的node實例是可變的:

n = node(3)
assert n.value == 3
n.value = 5
assert n.value == 5  # it was modified!

此外,您的函數無法返回任何值。 就您而言,這可能是錯誤的方法。 另外,坦率地說,我不明白為什么要在引用.next值的地方使用數字( 0n - 1 )。 這些必須是節點實例,而不是數字。

顯然,您正在執行鏈表的實現,並且您的foo函數試圖通過遍歷列表來刪除第n個節點。 (請注意描述性地命名您的功能;它有助於您和其他人回答您的問題。)

我就是這樣的:

class Node(object):  # class names are usually TitleCase
    def __init__(self, value, next=None):
        self.value = value
        self.next = next  # no properties for simplicity

    def __repr__(self):
        return "node({0})".format(self.value)


def asList(node):  # nice for printing
    if not node:
        return []
    return [node.value] + asList(node.next)


def removeNodeAt(head_node, index):
  """Removes a node from a list. Returns the (new) head node of the list."""
  if index == 0:  # changing head
    return head_node.next
  i = 1  # we have handled the index == 0 above 
  scan_node = head_node
  while i < index and scan_node.next:
    scan_node = scan_node.next
    i += 1
  # here scan_node.next is the node we want removed, or None
  if scan_node.next:
    scan_node.next = scan_node.next.next  # jump over the removed node
  return head_node

有用:

>>> n3 = Node(0, Node(1, Node(2)))
>>> asList(removeNodeAt(n3, 2))
[0, 1]

>>> n3 = Node(0, Node(1, Node(2)))
>>> asList(removeNodeAt(n3, 1))
[0, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM