简体   繁体   中英

Can a class variable be created inside one of the class' methods in Python?

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?

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 :)

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM