0

I want to make a variable that will return an integer that I can edit and change throughout my code to avoid using globals. I can't figure out how to simply make a function with a variable and call / edit it at will.

def variable():
    number = 0
    return number
    
print(variable())

variable.number +=1

print(variable())

For this bit of code I get this error

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [6], in <cell line: 7>()
      3     return number
      5 print(variable())
----> 7 variable.number +=1
      9 print(variable())

AttributeError: 'function' object has no attribute 'number'

but If I do it this way and externally set the variable equal to 1 I don't get an error but the return value is still equal to 0

    def variable():
    number = 0
    return number
    
print(variable())

variable.number =1

print(variable())

variable.number +=1

print(variable())

0
0
0

So for some reason the return value always produces 0 but if I explicitly call variable.number like this

print(variable.number)

the result will show the proper number that is produced when I set it to =1 and +=1. It's as if the return variable() and variable.number are two different objects even though they are based on the same 'number' variable within the function.

Can someone explain to me what is going on and how I'm supposed to properly create a dynamic variable that avoids global in this way?

thatoneguy
  • 59
  • 1
  • 11
  • You want a functor, but I don't know python well enough to tell you the magic name for the function. – Stephen Newell Jul 29 '22 at 21:26
  • Does this answer your question? [Create a functor as a callable class or as a nested function](https://stackoverflow.com/questions/34874849/create-a-functor-as-a-callable-class-or-as-a-nested-function) – Stephen Newell Jul 29 '22 at 21:28
  • Duplicate has the syntax you want (`__call__`) – Stephen Newell Jul 29 '22 at 21:29
  • All of those examples provide a memory location as the result. repr() doesn't work on them either. I just want a simple global variable replacement. What I posted above works, I just don't understand why it works the way it does, I can't use it if I can't understand it. – thatoneguy Jul 29 '22 at 21:43
  • Every time you call `variable` you execute the function which sets `number` to 0. – Stephen Newell Jul 29 '22 at 21:46
  • But if I don't set number to something then I can't call variable.number. – thatoneguy Jul 29 '22 at 21:49
  • Hence why you want a functor because it lets you associate state with a function. – Stephen Newell Jul 29 '22 at 22:11

1 Answers1

0

I figured it out. I did this

class Row_number:
    number = 604

    def __repr__(self):
        return repr(self.number)
row_number = Row_number()

Then I call row_number.number to call and edit the variable.

thatoneguy
  • 59
  • 1
  • 11