I am not able to understand the scope of few variables and why python is throwing an error while trying to do few things inside a class that is defined a method
Let me start with a basic example which works and then move on to few examples which work and which doesn't. I have an idea about what is working and sometimes what is not. But I feel that I lack an understanding the scope in this case (class inside a method)
First an example which works
Case 1:
def foo_method(a, b, c):
return b, c, a
def bar_method(a=1, b=2, c=3):
class BarClass:
a_ = a + 1
b_ = b + 1
c_ = c + 1
b_, c_, a_ = foo_method(a, b, c)
return BarClass()
When I try to run the above code it works i.e
temp = bar_method()
works with out any issue
Case 2:
def foo_method(a, b, c):
return b, c, a
def bar_method(a=1, b=2, c=3):
class BarClass:
a_ = a + 1
b_ = b + 1
c_ = c + 1
b, c, a = foo_method(a, b, c)
return BarClass()
Case 2 doesnt work i.e temp = bar_method()
throws the error NameError: name 'a' is not defined
Case 3:
def foo_method(a, b, c):
return b, c, a
def bar_method(a=1, b=2, c=3):
class BarClass:
a = a + 1
b = b + 1
c = c + 1
return BarClass()
Case 3 doesnt work i.e temp = bar_method()
throws the error NameError: name 'a' is not defined
Case 4
def foo_method(a, b, c):
return b, c, a
def bar_method(a=1, b=2, c=3):
class BarClass:
a_ = a + 1
b_ = b + 1
c_ = c + 1
a_ = a_ + 1
b_, c_, a_ = foo_method(a_, b_, c_)
return BarClass()
Case 4 works.
I got confused as to why certain operations are working and why others aren't. Can anyone shed some explanation on what I am not able to comprehend here. It seems like I can't make any modifications to the variables defined in the bar_method