0
Why is there a local error on a variable defined globally?
I’m talking about the variable x. https://code.sololearn.com/cn93NeiXpUkJ/?ref=app
3 Respostas
+ 5
class thing:
x = 0
def __init__(self,attr):
self.attr = attr
thing.x += 1
+ 4
Python assumes that the "x" in the class is a class attribute but as it has never been defined, you cannot increase it by 1.
If you want to use the global x, you could write
global x
x += 1
in the class.
+ 3
x = 0
class thing:
def __init__(self,attr):
self.attr = attr
global x
x += 1
thing1 = thing("t")
print(thing1.attr, x)