mymodule.py:
# -*- coding: utf-8 -*- import sys #导入整个string模块 print sys.path ''' 如果使用 from import sys 则本页可以直接使用stdout.write() 否则需要sys.stdout.write() ''' def Main(): sys.stdout.write("hello world! /n") if __name__ == "__main__": Main() import string #格式:模块名 import sys as ssss #格式:import 模块名称 as 模块新名 print string.capitalize("oooooo") from math import sqrt #格式: from 模块名称 import 函数名称 print sqrt(9) ''' 变量的类型是动态的 ''' i=1 print i,type(i),id(i) i=10000000000 print i,type(i),id(i) i=1.1 print i,type(i),id(i) #Python 既是一种动态类型语言,同时也是一种强类型的语言 i=10;j='ss' #print i+j#错误方式 print str(i)+j #类型 #空对象None #布尔类型 True和False #注意首字母要大写 #0、空字符串''、空元组()、表[]、空字典{}都被当做False,其他对象都为True if 0: print 'False' else: print 'True' #数值类型有四种:长整型、整型、浮点型、复数类型------------------------------ #超过整型的数会自动调整为长整型 #只有64位的双精度的浮点型float #复数:z.real . z.imag #数值类型计算强制提升原则:int,long,float,complex #关于货币计算,无decimal类型,但有decimal模块 #字符串可以用单引号,双引号,三引号来定义 #字符串有两种类型,str单字节字符序列,unicode 双字节字符序列 #关于换行,使用转义字符/n可以换,直接使用语句换行也可以达到目的 str = '/n my work /n' str1 = 'is very important!' str2 = '''oh,my god! really? I don't believe!''' print str,str1,str2 #unicode字符可以如下定义 str3 = u'我的工作' print str3 #------------------------------------------------------ #当使用 utf-8 编码时,非 unicode 字符中一个汉字的长度是 3,而使用 gb2312 时是 2 ustr = u'我' ostr = '我' print len(ustr),len(ostr) #输出 1 3 # -*- coding: gb2312 -*- ustr = u'我' ostr = '我' print len(ustr),len(ostr) #输出 1 2 # -*- coding: utf-8 -*- str1 = u'我是派森' print str1[2:4] #输出 '派森' #-------------------------------------------------------- #列表list类似C#的ArrayList,顺序存储 array = [1,2,3] print array[0] print array #Python 的列表中可以混合使用不同类型的数据,像['a', 2, 3]这样,这点像java的ArrayList ''' 切片指的是抽取序列的 一部分,其形式为:list[start:end:step]。其抽取规则是:从 start 开始,每次加上 step, 直到 end 为止。默认的 step 为 1;当 start 没有给出时,默认从 list 的第一个元素开始; 当 end=-1 时表示 list 的最后一个元素,依此类推。 ''' test = ['never', 1, 2, 'yes', 1, 'no', 'maybe'] print test[0:3] #包括test[0],不包括test[3] print test[0:6:2]#步长为2,即间隔1个 #元组与列表相似,但速度更快,不可变序列---------------------------------- test = [0] print type(test) test = [0,] print type(test) test = (0,) #元组可以这样定义 print type(test) test = (0) #但不能这样定义,Python 会认为它是一个括号表达式 print type(test) test = 0, #也可以省略括号,但要注意与 C 的逗号表达式不同 print type(test) #输出<type 'tuple'> #利用元组的这个特性,可以简化 Python 变量的初始化过程 x,y,z=1,2,3 a = 1 b = 2 a,b = b,a #结果是a、b的值交换了 print a,b #也可以利用C语言的交换法 tmp = a; a = b; b = tmp 进行a、b位置和值的交换 #python的set是无序的不重复的元素集合---------------------------------------- s = set(['a','b','c']) #python3以后是 s={'a','b','c'} #set中传入重复的元素会自动合并 a = [1,2,3,4,5,6,3,2,4] b = set(a) print b #类似数学当中的集合概念,可以进行交,并,差,补等逻辑运算 a = ['33','22','11'] b = ['33','44','55'] c = set(a)&set(b) #找出两个list里面相同的元素(集合求交集) print c #python里的哈希表就是字典了dict------------------------------------- #它包括关键字(key)和关键字对应的值(value) #dictionary = {key:value},当有多个键值对时,使用逗号进行分割。 #算数运算 + - * / % 还有求幕**和取整//-------------------------------- #python没有++和--运算,仅使用 x += 3 或 x = x + 3 #Python 用关键字 and、or、not 替代 && , || , ! #在 Python 中,and 和 or 所执行的逻辑运算并不返回布尔值,而是返回它们实际进行比较的值之一 print 'a' and 'b' print '' and 'b' #关系运算与其他语言相通,共6种==,!=,>=,<=,<,> #三元运算 # -*- coding: utf-8 -*- x = 4 print '偶数' if x % 2 == 0 else '奇数' #乱码? #条件语句 if,elif,else --------------------------------- #如果一个流程控制分支下不做任何事情,记得写一句 pass 语句,不然 Python 会报错 if 0: pass # 使用 if 替代 if x =='1': print 'one' elif x=='2': print 'two' else: print 'nothing!' # 使用 dict numtrans = { 1: 'one', 2: 'two', } try: print numtrans[x] except KeyError: print 'nothing1' # 也可以在分支中使用方法(函数) def print_one(): print 'one' def print_two(): print 'two' numtrans = { 1:print_one, 2:print_two, } try: print numtrans[x]() #注意名字+括号就可以执行方法了,这个实际上很牛 X 的 except KeyError: print 'nothing2' #python 只支持while 和for 循环-------------------------------------------- for i in [1,2,3,4,5]: print i ''' for i range(10): s#等同xrange(10)相当于for(int i = 0; i < 10; i++) print i ''' #xrange 返回的是一个不可改变的XRangeType 对象。 #这是一个迭代器,也就是只有用到那个数时才临时通过计算提供值。 #当 j 值很大时,xrange 能更有效地利用内存 #Python 中的 while 和 for 循环中支持 break 和 continue 语句。 #break 语句用于立刻中止循环,continue 语句用于直接 进入下一次循环(忽略当前循环的剩余语句)。 #Python 中的循环还支持 else 语句,它只在循环正常完成后运行 #或者在循环条件不成立时立即运行(仅 while 循环) #或者迭代序列为空时立即执行(仅for循环) #如果循环当中使用了break退出,则else忽略 #while-else while i<10: i = i+1 else: print 'done' s = ['cc','bb','aa'] #for-else for k in s: if k=='aa': print 'got it' break else: print 'not found' #异常------------------------------------------------------ # try/except/finally/raise 结构 对应java和C#的 # try/catch/finally/throw ''' try: f = open('file.txt') s = f.readline() except IOError,(errno,strerror): print "I/O error(%s):" %(errno,strerror) except ValueError: print "could not convert data into Integer." except: print "Unexpected error:", sys,exc_info()[0] raise finally: f.close() ''' #列表内涵------------------------------------------------------ #列表内涵的一个著名例子是生成九九乘法表: s = [(x, y, x*y) for x in range(1, 10) for y in range(1,10) if x>=y] print s #列表内涵可分为三部分,最左边是生成每个元素的表达式 #中间是for迭代过程,最右边是可以设定if判断的过滤条件 s = [x for x in range(0,10) if x%2 ==0] print s #动态表达式 数学计算eval——------------------------------------------ str = '1+2' print eval(str) print str #将字符串当成代码来执行---exec exec 'a=100' print a #函数我来了----------------------------------------------------------- #定义没有参数,也无返回值的函数 def F1(): print 'hello kitty' F1() #定义有参数和一个返回值的函数 def F2(x,y): a = x+y return a print F2(3,4) #定义有多个返回值的函数,用逗号分隔不同的返回值,返回结果是一个元组 def F3(x,y): a = x/y b = x%y return a,b print F3(6,4) #参数类型没有约束,支持泛型编程,可以输入任意类型的参数数据 #python的参数提供了四种类型 #1. f(arg1,arg2,...) #2. f(arg1=1,arg2=2,..argn=n) 给参数提供了默认值,关键参数 #3. f(*arg) arg 代表了一个tuple,类似参数列表,接收多个参数 #4. f(**arg) 传入的参数在函数内部保存在一个叫arg的dict中,掉用的时候使用f(a1=v1,a2=v2)的形式 def parrot(voltage,state='a stiff',action='voom',type='norwegian blue'): print "--this parrot wouldn't",action print "if you put",voltage,"volts through it" print "--Lovely plumage,the",type print "--it's", state #正确调用方式 parrot(1000) parrot(action='vooom',voltage=10000)#关键字,缺省值,次序可变 parrot('a thousand', state='pushing up the daisies') parrot('a million','dereft of life','jump')#位置参数,缺省值 #以下是错误类型 #parrot()#非缺省值的参数没有提供 #parrot(volage=5,'dead')#关键参数后面又出现非关键字参数 #parrot(110, voltage=220) # 参数值重复提供 #parrot(actor='John Cleese') # 未知关键字 #字典参数------------------------------------------------- def cheeshop(**keywords): for i in keywords.keys(): print i,':',keywords[i] cheeshop(client='johon',shopkeeper='paliin',skecth='skectch') ''' * 通过位置分配非关键字参数 * 通过匹配变量名分配关键字参数 * 其他额外的非关键字参数分配到*name 元组中 * 其他额外的关键字参数分配到**name 的字典中 * 用默认值分配给在调用时未得到分配的参数 ''' #lambda 函数是匿名函数,用来定义没有名字的函数对象。 #在 Python 中,lambda 只能包含表达式:lambda arg1, arg2 ... : expression。 #lambda 关键字后就是逗号分隔的形参列表,冒号后面是一个表达式,表达式求值的结果为 lambda 的返回值。 n=2 print n**4 #高级函数-------------------------------------------------------------------- #map映射,也就是将算法施于容器中的每个元素,将返回值合并为一个新的容器 def map_func(s): return s + 1 s = [1,2,3,4,5] map1 = map(map_func,s) print map1 #filter过滤,将算法施于容器中的每个元素,将返回值为真的元素合并为一个新的容器。 def filter_func(s): if s % 2 == 0: return True else: return False filter1 = filter(filter_func, s) #得到s中能被 2 整除的 print filter1 #reduce 合并,将算法(可能携带一个初值)依次施于容器中的每个元素,将返回值作为下 #一步计算的参数之一,与下一个元素再计算,直至最终获得一个总的结果。 def reduce_func(s, lis): return s + lis reduce1 = reduce(reduce_func, s) print reduce1 #类 class----------------------------------------------------------------------- class A: pass #相当于class A{} #类的实例化 a = A() #将类当做一个函数调用 #python是动态语言,所以你可以不在类定义中添加成员变量,可以在运行时动态添加他们 class A:pass a = A() a.x = 1 print a.x #方法好,但最好是在类的初始化函数里面就声明并初始化 #初始化函数,java有,C#也有 #python提供的是:__init__ 类在实例化时会首先调用这个函数,我们可以重写这个函数来完成一些开始工作 class A: def __init__(self): self.x = 3 a = A() print a.x class A: def __init__(self,x): self.x = x a = A(1) print a.x #静态变量----------------------------------------------------------------- class A: y=2 print A.y #对象可以直接访问类的静态成员添加了一个非静态成员 y #但对象不能为类的静态成员赋值 b = A() b.y = 3888 print b.y print A.y #b.y=3 相当于为实例 a 添加了一个非静态成员 #而类 A 的静态成员A.y 没有发生改变,即使同名也不会冲突,因为它们不在同一个命名空间内 #私有成员------------------------------------------------------------------ #python并没有严格意义上的私有成员,这是建议加下划线,不是严格意义上封装 class A: def __init__(self): self.__x = 999 a = A() #错误 print a.__x print a._A__x #!!!! #类方法----------------------------------------------------------------- #在类中定义的常规方法的第一个参数总是该类的实例,即 self。这点要非常注意 class A: def prt(self): print "my name is A" def reprt(self): #prt(self)#错误方式 A.prt(self)#正确,内部方法中引用类的另一个方法必须使用类名加方法名! a = A() a.prt() a.reprt() #类的静态方法------------------------------------------------ #java和C#用static,而python用@staticmethod class A: @staticmethod def prt(): print "my name is Liao" A.prt() #类不支持方法重载,前面定义的方法会被后面定义的方法所覆盖 #类的继承---------------------------------------------------- #单继承--用类名后加括号的方式实现继承 class A: x=111 y=333 class B(A): x=2 print B.x,B.y #如果子类中直接调用父类的方法,java中可以直接使用this. #BaseClass.method(self,arguments) #pathon支持多继承,java和C#中则用接口实现 #可以 class B(A,D,E)这样来继承,如果有重名属性时则有搜索顺序 #接口和抽象类---------------------------------------------------------- #在 Python 这类动态编程语言中,我们经常需要检查一个类、对象或模块,以确定它是什么、它知道什么或它能做什么。 #在 Python 中,我们把这类功能叫做自省(Introspection) ''' * 对象的名称是什么(__name__)? * 这是哪种类型的对象(__class__)? * 对象知道些什么(__doc__)? * 对象能做些什么(__dict__)? * 对象(的类)继承自谁(__bases__)? * 它在哪一个模块中(__module__)? ''' print A.__module__ #print A.__class__ print A.__name__ print A.__doc__ print A.__dict__ print B.__bases__ #Python 提供了很多有用的自省函数,帮助我们找到对象信息 ''' * id() 返回对象唯一的标识符 * repr() 返回对象的标准字符串表达式 * type() 返回对象的类型 * dir() 返回对象的属性名称列表 * vars() 返回一个字典,它包含了对象存储于其__dict__中的属性(键)及值 * hasattr() 判断一个对象是否有一个特定的属性 * getattr() 取得对象的属性 * setattr() 赋值给对象的属性 * delattr() 从一个对象中删除属性 * callable() 测试对象的可调用性 * issubclass() 判断一个类是另一个类的子类或子孙类 * isinstance() 判断一个对象是否是另一个给定类的实例 * super() 返回相应的父类 ''' a = A() #print a.id() #?? #print a.id() import sys print sys.path import os as system #创建包package-------------------------------------------- #1.建立一个文件夹,名字为name #2.在这个目录下创建__init__.py的文件 #3.根据需要存放脚本文件 #只要目录下存在__init__.py就表明此目录作为一个package包处理 # 这个初始文件可以是空文件,也可以设定一些常量,如__all__ = ["m1", "m2", "m3"] # 表明import * 会导入这个三个文件模块,没定义则不保证会导入,除非impot详细写明模块名字