简体   繁体   中英

Using parameters to pass values between functions

I am currently having an issue, as i am relatively new to python , it might be a very easy solution for others.

I want to pass a parameter between both functions 'eg1' and 'eg2', there is a common number the user will input (example:10) then 'eg1' will add 1 to it and 'eg2' will take the final value of 'eg1' and add 1 more to it, (example: 10 will become 11 then 12)

It is troubling me because this keeps popping up:

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'

I can't seem to find my mistake.

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)

Reference for parameter passing: Python definition function parameter passing

  • 'Print' with nothing means to leave an empty line, for me

  • I messed up the title, fixed.

Since you are already using a class, you can pass the number you want to increment twice as an instance attribute, and call your increment functions on that attribute. This will avoid passing the updated value after calling one in the method two

Calling one and then two makes sure that two is working on the updated value after calling one .

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

Based on your comments, here's one way to get the result. I am using 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM