Home > OS >  Creating or modify function variable from outer scope python
Creating or modify function variable from outer scope python

Time:11-11

I wrote this code and received an unexpected output than I thought.

def egg():
    print(a)

egg() # NameError: name 'a' is not defined **As excepted**

egg.a = 50

egg() # NameError: name 'a' is not defined **Not as excepted**

My hope was that after setting agg.a = 50 the next time I would call agg() a variable will be defined.

Can someone please explain what am I missing? why a is not added to the function scope dynamically

p.s. when I used dir(egg) I could see a was add the the function dict

CodePudding user response:

uisng non local params

def main():
    def egg():
        nonlocal a
        print(a)

    #egg() # NameError: name 'a' is not defined **As excepted**

    a = 50

    egg()
main()

output

50

CodePudding user response:

Callable class can be used to replicate this sort of behaviour without breaking the encapsulation of a function.

class Egg:
    def __init__(self, a):
        self.a = a
    def __call__(self):
        print(self.a)

egg = Egg(50)

egg() # 50

egg.a = 20

egg() # 20
  • Related