[英]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
值的地方使用数字( 0
, n - 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.