簡體   English   中英

將 arguments 傳遞給 function(Python,OOP,函數)

[英]Passing arguments to the function (Python, OOP, functions)

So here we are passing 2 arguments to the function: 1) a just created object from the class ( counter ) and 2) a number ( 0 ).

def increment(c, num):
    c.count += 1
    num += 1



class Counter:
    def __init__(self):
        self.count = 0
 
 
counter = Counter()
number = 0
 
for i in range(0, 100):
    increment(counter, number)
 
print(
    "counter is "
    + str(counter.count)
    + ", number of times is "
    + str(number)
)

代碼結果如下:

# counter is 100, number of times is 0

為什么“數字”變量不增加,如果 function 清楚地說:

num += 1

???

每次調用 function 時,都會將值分配給一個名為num的新變量。 我不會修改變量。

因此,您必須從增量 function 返回number的值並將其分配給 number 變量。

def increment(c, num):
    c.count += 1
    return num+1



class Counter:
    def __init__(self):
        self.count = 0
 
 
counter = Counter()
number = 0
 
for i in range(0, 100):
    number = increment(counter, number)
 
print(
    "counter is "
    + str(counter.count)
    + ", number of times is "
    + str(number)
)

Output

counter is 100, number of times is 100

最好的方法是在計數器 class 中添加增量 function。 但是如果你想用 function 做到這一點,這種方式工作正常。

Python 通過 object 引用傳遞參數,這基本上導致引用可變類型和不可變類型的值。

Counter是您創建的可變 class ,而number是 integer (不可變)。

如其他答案和評論中所述,不可變的 integer 被覆蓋,但由於它是一個局部變量,因此您無法在 function 之外看到這些更改,除非您從increment中返回num的值。

或者,您可以將number設為Counter的 class 變量。 因此,您可以跟蹤任何Counter實例增加計數的次數:

class Counter:
    number_increases = 0

    def __init__(self):
        self.count = 0

    def increase(self):
        self.count += 1
        Counter.number_increases += 1


c1 = Counter()
c2 = Counter()

for i in range(10):
    c1.increase()

print(f"counters are {c1.count} and {c2.count}; " +
      f"number of times is {Counter.number_increases}")

for i in range(20):
    c2.increase()

print(f"counters are {c1.count} and {c2.count}; " +
      f"number of times is {Counter.number_increases}")

Output:

counters are 10 and 0; number of times is 10
counters are 10 and 20; number of times is 30

這是因為每當您將參數傳遞給 python 中的 function 時,您使用的是該參數的副本,因此寫入n += 1不會影響 ZC1C425268E68385D1AB5074C14A 之外的實際變量 n。 你可以試試寫:

def increment(c, num):
    c.count += 1
    return num+1

for循環中,您可以這樣做:

for i in range(100): # range(0, 100) is the same as range(100)
                     # because 0 is the default value for start
    number = increment(counter, number)

那應該行得通。

暫無
暫無

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

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