-1

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.

beepbeep-boop
  • 204
  • 1
  • 2
  • 11
  • What are you trying to do on line `b = a.d`? – alamoot Dec 31 '19 at 07:47
  • Just do `b = one(a)`. – Ajay Dabas Dec 31 '19 at 07:49
  • alamoot i am trying to get the final value of the function eg1 and get its value in the function eg2 – beepbeep-boop Dec 31 '19 at 07:50
  • Ajay Dabas i know that works but i am hoping there is more ways to that, sometimes i might have a 'print' in my function and then i will not be able to get its value from another function. – beepbeep-boop Dec 31 '19 at 07:51
  • `print()` prints something on the screen. `return` returns something from a function, but it is preserved only if you store it where the function was called from. You could make an attempt of describing what the lines in this code are meant to do, and then it would be easier to fix them to really do what you intended. – tevemadar Dec 31 '19 at 08:04

2 Answers2

1

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
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

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())
YOLO
  • 20,181
  • 5
  • 20
  • 40