-1
class A:
    x=10
    def fn(self):
        print(x)

I tried running this code, but an error comes out as:

NameError: name 'x' is not defined

inside the function block if i put self.x then it works perfectly my doubt is why doesnt the above code work properly x is defined in class scope,so shouldnt it be accessable to all functions defined in class as class_variable also

Gaurav Kochar
  • 11
  • 1
  • 6
  • From the [docs](https://docs.python.org/3/reference/executionmodel.html#resolution-of-names): *The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods*. More details in the duplicate. – wim Nov 06 '20 at 05:01

1 Answers1

-1

Inside class it is a local variable, you can assign it to a property of the class and get it:

class A:
  def __init__(self):
    x=10
    self.x = x
    def fn(self):
      print(self.x)
Wasif
  • 14,755
  • 3
  • 14
  • 34