python中的不可變類型的全局變量如int a=1,str b='hello', 若需要修改必須加global申明, 而全局變量是可變類型的,如list, dict ,則直接修改list.append(),dict[x]=xx, 無需申明。
若全局變量與局部變量同名, 采用就近原則。
1 c=[1,2,3,4,5] 2 d=2
3 e='HELLO'
4 f={'name':'xx','age':18} 5 class A: 6 b=[1,2,3] 7 d=222
8 def hehe(self): 9 self.b.append(4) 10 self.d=333
11 c.append(6) 12 global e 13 d=3
14 e=e.lower() # 必須global e 才不報錯
15 f['age']=20
16 print(self.b,c,d,e,f,self.d) 17 def haha(self): 18 print(self.b,c,d,e,f,self.d) 19 if __name__ == '__main__': 20 a = A().hehe() 21 A().haha()
output:
[1, 2, 3, 4] [1, 2, 3, 4, 5, 6] 3 hello {'name': 'xx', 'age': 20} 333
[1, 2, 3, 4] [1, 2, 3, 4, 5, 6] 2 hello {'name': 'xx', 'age': 20} 222
原因在於int類型str類型,tuplel類型,只有一種修改方法,即x = y, 恰好這種修改方法同時也是創建變量的方法,所以產生了歧義。