Home > Net >  How to dynamically get function variables
How to dynamically get function variables

Time:05-31

My requirement is that the parameters and variables of the function must be consistent.

def func(i):
    # body
    return i

for i in ['GetA', 'GetB', 'GetC']:
    # name = f"{i}"
    exec(f"{i}=func({i})")

print(GetA)
print(GetB)
print(GetC)
    exec(f"{i}=func({i})")
  File "<string>", line 1, in <module>
NameError: name 'GetA' is not defined

CodePudding user response:

I think you have to define them first.

# here I defined the variable
name1 = ""
name2 = ""
name3 = ""
for i in range(1, 4):
    name = f"name{i}"
    exec(f"{name} = func{i}({i})")

print(name1, name2, name3)

CodePudding user response:

you forgot the '' around the variable name, change the exec line with this:

exec(f"{name} = func{i}('{name}')")

  • Related