[英]Passing object parameter by value
码:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def length(stack):
i = 0
while not stack.is_empty():
stack.pop()
i += 1
return i
s1 = Stack()
s1.push(3)
s1.push(2)
s1.push(1)
print(length(s1))
s1.pop()
输出:
3
Traceback (most recent call last):
File "Stack.py", line 26, in <module>
s1.pop()
File "Stack.py", line 12, in pop
return self.items.pop()
IndexError: pop from empty list
我希望函数length()
能够修改s1
的副本,而不是更改s1
。 有什么办法可以在python中做到这一点吗?
我不允许直接使用s1.items
所以我不能只使用s1[:]
。 我也不能修改该类。
您可以简单地使用copy
模块:
import copy
# ... your code ...
print(length(copy.deepcopy(s1))) # pass a copy to the length function
或者,如果您希望它没有额外的模块,并且您可以更改length
功能,则可以简单地保留pop
项目,并在达到长度后再次push
其push
:
def length(stack):
i = 0
tmp = []
while not stack.is_empty():
tmp.append(stack.pop()) # append them to your temporary storage
i += 1
for item in tmp: # take the items saved in the temporary list
stack.push(item) # and push them into your stack again
return i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.