0

Touching on the following question posted on SO, Python - why use "self" in a class?, I was wondering:

If I created a variable inside a method of a given class without using the "self.", will it be a class variable? And if this is not the case, why not?

So for instance if I have a class like so:

class A:
    def somefunction(self):
        x=1

Will x be a class variable?

Community
  • 1
  • 1
user1491307
  • 159
  • 1
  • 8

3 Answers3

3

Actually no. Because of x is not class variable - it is local variable of method somefunction.

Class variable should be defined exactly in the class body:

class A:
    x = 1
    def somefunction(self):
        A.x += 1
        print A.x

BTW: even if you had defined classvariable correct, you would anyway got output:

2
2

because of in somefunction you're assigning x=1, so each time this function is run value of x is reset to 1 :)

RomanHotsiy
  • 4,978
  • 1
  • 25
  • 36
  • I should actually rephrase my question to "can class variables be created in methods" – user1491307 Jul 18 '14 at 15:51
  • Possibly.., most likely yes. You actually shouldn't ask questions before searching it in Google. – RomanHotsiy Jul 18 '14 at 15:54
  • No, of course I have searched it, but with the added information I got from your answer/comment, the question can be rephrased to be more succinct and meaningful. – user1491307 Jul 18 '14 at 16:02
  • You changes made my answer confusing :( – RomanHotsiy Jul 18 '14 at 16:11
  • Oh sorry.. But I think your answer makes perfect sense, apart from the last few lines explaining my example, which i have deleted. As you have pointed out, the function gets called multiple times, so the variable is reset/recreated and I think there is another reason it wouldn't work, namely because _x_ is immutable, so it seems to me that it would be just confusing to have it in this question. – user1491307 Jul 18 '14 at 16:19
1

Whenever you assign a variable in a Python function, it's created in the innermost local namespace by default. You aren't referring to a variable in a different namespace (like the A class) unless you explicitly declare it. So in your code, you're creating x in a local namespace, which is specific to that function - not even specific to that instance of A, since you didn't declare it as self.x. I believe that is why you get 2,2 instead of 2,3.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
1

No, your assumption is wrong. It is a local variable.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895