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

17th Nov 2022, 10:15 PM
Margaret Guzman
Margaret Guzman - avatar
3 Réponses
+ 5
class thing: x = 0 def __init__(self,attr): self.attr = attr thing.x += 1
17th Nov 2022, 11:30 PM
SoloProg
SoloProg - avatar
+ 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.
17th Nov 2022, 11:24 PM
Lisa
Lisa - avatar
+ 3
x = 0 class thing: def __init__(self,attr): self.attr = attr global x x += 1 thing1 = thing("t") print(thing1.attr, x)
18th Nov 2022, 12:08 AM
Solo
Solo - avatar