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, 恰好这种修改方法同时也是创建变量的方法,所以产生了歧义。