簡體   English   中英

使用參數在函數之間傳遞值

[英]Using parameters to pass values between functions

我目前遇到了一個問題,因為我對 python 比較陌生,對其他人來說可能是一個非常簡單的解決方案。

我想在兩個函數“eg1”和“eg2”之間傳遞一個參數,用戶將輸入一個通用數字(例如:10)然后“eg1”將加1,“eg2”將取最終值'eg1' 再添加 1,(例如:10 將變成 11 然后是 12)

這讓我很困擾,因為它不斷出現:

Traceback (most recent call last):
  File "example.py", line 69, in <module>
    eg2(a)
  File "example.py", line 63, in eg2
    b = a.d
AttributeError: 'int' object has no attribute 'd'

我似乎找不到我的錯誤。

class Helper:pass
a = Helper()

def one(a):
   d = a
   d += 1
   print d

def two(a):
   b = a.d
   b += 1
   print b

print

print ("Please enter a number.")
a = int(input('>> ')

print
one(a)

print
two(a)

參數傳遞參考: Python定義函數參數傳遞

  • 對我來說,沒有任何內容的“打印”意味着留下一個空行

  • 我把標題搞砸了,修復了。

由於您已經在使用一個類,因此您可以將要遞增兩次的數字作為實例屬性傳遞,並在該屬性上調用遞增函數。 這將避免在方法two調用one后傳遞更新的值

調用onetwo可確保在調用one后, two正在處理更新的值。

class Helper:

    # Pass num as parameter
    def __init__(self, num):
        self.num = num

    # Increment num
    def one(self):
        self.num += 1

    # Increment num
    def two(self):
        self.num += 1

h = Helper(10)
h.one()
print(h.num) # 11
h.two()
print(h.num) # 12

根據您的評論,這是獲得結果的一種方法。 我正在使用python3:

class Helper:
    d = None

cl = Helper()

def one(a):
    cl.d = a
    cl.d += 1
    return cl.d

def two():
    cl.d += 1
    return cl.d

print ("Please enter a number.")
a = int(input('>> '))

print(one(a))

print(two())

暫無
暫無

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

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