Home > Blockchain >  How to create a dynamic variable, avoiding globals?
How to create a dynamic variable, avoiding globals?

Time:08-01

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?

CodePudding user response:

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.

  • Related