python能够改变变量作用域的代码段有:lamaba、def、class
if/elif/else、for/while、try/except/finally不能改变变量的作用域范围,在这些代码段中的变量,外部也能访问;
变量的访问路径:
local:比如function中的变量所在的作用域就是local的。简称L
enclosing:某个function被嵌套后的上一层function的作用域。简称E
global:当前模块中的全局作用域。简称G
built-in:python内置作用域.简称B
对某个变量搜索的顺序是:local>enclosing>global>built-in。也就是LEGB
def片段:
a =100 def change(): a = 200 print a if __name__ == '__main__': print a change() 结果: 100 200
结论:def代码段的a与全局的a是不同的作用域,互不干扰
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在分配之前就先访问,所以报错
想要避免这种问题:
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
类变量访问: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