python可以改變變量做用域的代碼段有:lamaba、def、class html
if/elif/else、for/while、try/except/finally不能改變變量的做用域範圍,在這些代碼段中的變量,外部也能訪問; python
變量的訪問路徑: 編程
local:好比function中的變量所在的做用域就是local的。簡稱L
enclosing:某個function被嵌套後的上一層function的做用域。簡稱E
global:當前模塊中的全局做用域。簡稱G
built-in:python內置做用域.簡稱B
對某個變量搜索的順序是:local>enclosing>global>built-in。也就是LEGB 函數
def片斷: ui
a =100 def change(): a = 200 print a if __name__ == '__main__': print a change() 結果: 100 200
結論:def代碼段的a與全局的a是不一樣的做用域,互不干擾 spa
a =100 def change(): print a a = 200 print a if __name__ == '__main__': print a change()
UnboundLocalError: local variable 'a' referenced before assignment
本地變量在分配前被調用:在def函數未被運行時先進行預編譯;def片斷中的第一個print a在分配以前就先訪問,因此報錯 code
想要避免這種問題: htm
a =100 def change(): global a print a a = 200 print a if __name__ == '__main__': print a change() 結果: 100 100 200
def change(): a = 200 print a if __name__ == '__main__': print a change()
NameError: global name 'a' is not defined
類變量和實例變量: 對象
實例變量訪問:self.propertyName blog
類變量訪問:className.propertyName
class Person: name = "class global name" def __init__(self, newPersionName): self.name = newPersionName def sayYourName(self): print 'My name is %s'%(self.name); # -> class global name print 'name within class Person is actually the global name: %s'%(name); #-> whole global name print "only access Person's name via Person.name=%s"%(Person.name); # -> class global name def selfAndInitDemo(): ApersionInstance = Person("instance name crifan") ApersionInstance.sayYourName() BpersionInstance = Person("instance name simith") BpersionInstance.sayYourName() print "whole global name is %s"%(name); # -> whole global name if __name__=="__main__": selfAndInitDemo()
My name is instance name crifan name within class Person is actually the global name: whole global name only access Person's name via Person.name=class global name My name is instance name simith name within class Person is actually the global name: whole global name only access Person's name via Person.name=class global name whole global name is whole global name
實例變量新增不會改變類變量,而類變量的變化會直接影響到實例變量
class people: country = 'china' p1 = people() people.age = 10 # 類變量增長age p1.name = 'syc' # 實例變量增長name p1.country = 'japan' # 實例變量country進行修改 print p1.country # japan print people.country # china print people.age # 10 print p1.age # 10 print people.name # AttributeError: class people has no attribute 'name' print p1.name # syc
關於python面向對象編程的連接:
http://www.cnblogs.com/dolphin0520/archive/2013/03/29/2986924.html