Python scope inside nested function inside class?

How to set a class variable inside a function inside another function?

var.py

class A: def __init__(self): self.a = 1 self.b = 2 self.c = 3 def seta(self): def afunction(): self.a = 4 afunction() def geta(self): return self.a 

run.py

 cA = A() print cA.a cA.seta() print cA.a print cA.geta() 

python run.py

 1 1 1 

why not 4 and how can I make it equal to 4?

Edit:

Thanks to everyone - sorry, I just saw. I accidentally was disconnected _ in one of my names .... so my realm is actually all right.

+15
source share
5 answers

The problem is that there are several self variables. The argument passed to your inner function overwrites the scope of the outer.

You can overcome this by removing the self parameter from the internal function and making sure that you somehow call this function.

 class A: def __init__(self): self.a = 1 self.b = 2 self.c = 3 def seta(self): def afunction(): # no self here self.a = 4 afunction() # have to call the function def geta(self): return self.a 
+13
source

As already mentioned, afunction never called. You can do something like this:

 class A: def __init__(self): self.a = 1 def seta(self): def afunction(self): self.a = 4 afunction(self) def geta(self): return self.a a = A() print aa a.seta() print aa 

Here we actually call afunction and explicitly pass it self , but this is a pretty dumb way to set the a attribute - especially when we can do it explicitly, without the need for getters or seters: aa = 4

Or you could return execute a function:

 def seta(self): def afunction(): #Don't need to pass `self`. It gets picked up from the closure self.a = 4 return afunction 

and then in the code:

 a = A() a.seta()() #the first call returns the `afunction`, the second actually calls it. 
+2
source

Inside seta you define a function

  def afunction(self): self.a = 4 

... which would set self.a to 4 if it would ever be called. But it is not called anywhere, so a does not change.

+1
source

As some others have said, at some point you need to actually call the function. Comments won't let me type this wisely, so here is the answer:

 def seta(self): def functiona(self): #defined self.a = 4 functiona() #called 
-one
source

How can you make this equal to 4:

 class A: def __init__(self): self.a = 1 self.b = 2 self.c = 3 def seta(self): ##def afunction(self): (remove this) self.a = 4 def geta(self): return self.a 

The hard part: why it doesn't fit 4 ...

Currently a is set to 4 only through "afunction". Since a function is never called, it is never executed. The grid has a “function” nested inside, but not called ... like member variables in classes.

-one
source

All Articles