簡體   English   中英

通過值傳遞對象參數

[英]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項目,並在達到長度后再次pushpush

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.

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