python知识点积累
python知识点积累
1、异常处理
exception与else连用,else条件与exception平行
a = [1,10,6,3,10,1] def chushu(x): return 2000/x try: b = map(chushu,a) #except ZeroDivisionError: #print ZeroDivisionError,'0 not' except Exception: print Exception,'0 qu' else: print 'else-----' print b print '111'
2、面向对象常用术语
一般情况对象调用 属性(普通字段),普通方法
一般类调用 静态字段 ,静态方法(对象参数),类方法(cls)
总结:在类方法中定义的普通方法 cls不能调用 self在没有被传入前不能被使用
class Foo(object): NUM = 3 def __init__(self): self.name = "zhang" self.n = 5 def aa(self): print "aa" @classmethod def jihua(cls): print "jihuan" def cc(self): print self.name print "jin---c" print "cc" cls.aa = cc def bb(self): print "jin------b" print "bb" a = Foo() a.aa() Foo.jihua() a.aa()
意义:类方法可以对类本身进行操作,在现实中相当于自进化。
3、全局变量
函数外定义字典,函数内调用(未重新定义)则说明字典为全局字典。
而变量却不能直接在函数中调用(在未定义前)。
aa = {} c = 0 def at(i): #global c print "%s in"%at aa[i] = i c = c+1 l = ["1","2","3"] for i in l: at(i) print aa print c
>>> <function at at 0x027A7E70> in Traceback (most recent call last): File "C:/Python27/aaquanju.py", line 11, in <module> at(i) File "C:/Python27/aaquanju.py", line 7, in at c = c+1 UnboundLocalError: local variable 'c' referenced before assignment >>>
只要在函数内重新定义了字典或是变量,就都和全局的字典和变量无关了。
aa = {} c = 0 def at(i): #global c aa = {} aa[i] = i c = 100 l = ["1","2","3"] for i in l: at(i) print aa print c >>> {} 0 >>>
函数中调用全局的规则为 字典默认调用,变量直接调用会产生错误,必须先global 变量。
aa = {} c = 0 def at(i): global c aa[i] = i c = 100 l = ["1","2","3"] for i in l: at(i) print aa print c >>> {'1': '1', '3': '3', '2': '2'} 100 >>>
from浅谈