Python variable scope

Posted on 2013-11-13 00:07:37 +0900 in Technique Python Variable scope

About variable scope

In python, the variable scope has four kinds:

  • global
  • class
  • instance
  • local

In those kinds, the class-based and instance-based may merge in some cases:

Every time, the instance-based is looked up, which has not been initialized, the class-based result will be returned if there is any. Once it is initialized, it will be in the field of the instance.

One example from stackoverflow:

class MyClass(object):
    my_var = 10

    def __init__(self):
        print(self.my_var)


m1 = MyClass()
>>> 10          # class-based 

MyClass.my_var = 20
print(m1.my_var)
>>> 20          # Only class-based available.

m2 = MyClass()
>>> 20          # class-based

m1.my_var = 30
print(MyClass.my_var)
>>> 20          # class-based,but the instance-based variable has been set in m1.

MyClass.my_var = 40 
print(m1.my_var)
>>> 30           
                 # The value WAS shared before m1.my_var = 30 had happened.

print(m2.my_var)
>>> 40           # m2.my_var's value is still shared 
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | Modeling-Relationship-in-App-Engine »

Hide Comments

comments powered by Disqus