python实例练习

        最近学习python,看过几个星期的书。想到上学的时候学习c语言,复习考计算机二级阶段,有个300题题库做了好几遍,题目虽然基础,但是做了编码更规范了,对一些常见的代码设计心中也更有底了。因此我就找了一些python实例题目,练练手。现在记录下来督促自己每天保持日均5题的速度,提高效率。

参考资料1:https://www.runoob.com/python/python-100-examples.html

参考资料2:https://blog.csdn.net/weixin_41084236/article/details/81564963#056_1059

       在安装RF自动化测试工具时已经安装了python2.7。从我RF的代码里抠出了一个基本结构,命名为test.py,放置于D盘主目录。用cmd 命令 python d:\test.py,来查看运行结果。

      某天,我意识到python3.X是向前不兼容的。使用最新的python3.X来学习才是正确的方法,我于是安装了此时最新的python3.8和最风靡的pycharm来写代码。此时我已经做了75道题目,因此下面练习题1--75是在python2.7上测试通过的。76以后是python3.8上测试通过的。

 

test.py的结构

# coding=utf-8
import sys

#编码格式处理
if sys.version_info.major == 2:  # python2
    if sys.getdefaultencoding() != 'gbk':
        reload(sys)
        sys.setdefaultencoding('gbk')

def testfunc():

#编写测试练手代码的地方


#主函数
if __name__ == '__main__':
    testfunc();

 

练习题部分

1.有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
    def testfunction():
        total=0
        for i in range(1,5):
            for j in range(1,5):
                for k in range(1,5):
                    if ((i!=j)and(j!=k)and(k!=i)):
                        print(i,j,k)
                        total+=1
        print ("total number is: "+str(total))

2.企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
def testfunc():
    profit=int(input('How much is the profit: '))
    bonus=0
    thresholds=[100000,100000,200000,200000,400000]
    rates=[0.1,0.075,0.05,0.03,0.015,0.01]
    for i in range(len(thresholds)):
        if profit<=thresholds[i]:
            bonus+=profit*rates[i]
            profit=0
            break
        else:
            bonus+=thresholds[i]*rates[i]
            profit-=thresholds[i]
    bonus+=profit*rates[-1]
    print('the bonus is %d'%(bonus))

3.一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
    def testfunction(self,input):
        n=0
        while (n+1)**2-n**2<=168:
            n+=1
        print('the number is %d' %(n+1))

4. 输入某年某月某日,判断这一天是这一年的第几天?
def isLeapYear(y):
    return (y%400==0 or (y%4==0 and y%100!=0))

def testfunc():
    DofM=[0,31,28,31,30,31,30,31,31,30,31,30]
    res=0
    year=int(input('Year:'))
    month=int(input('Month:'))
    day=int(input('day:'))
    if isLeapYear(year):
       DofM[2]+=1
    for i in range(month):
        res+=DofM[i]
    print('it is %dth day of year' %(res+day))

5.输入三个整数x,y,z,请把这三个数由小到大输出
def testfunc():
    raw=[]
    for i in range(3):
        x=int(input('int%d: '%(i)))
        raw.append(x)
    
    for i in range(len(raw)):
        for j in range(i,len(raw)):
            if raw[i]>raw[j]:
                raw[i],raw[j]=raw[j],raw[i]
    print('The order of three digits from small to large is %s' %(raw))
或者
def testfunc():
    raw=[]
    for i in range(3):
        x=int(input('int%d: '%(i)))
        raw.append(x)
    print('The order of three digits from small to large is %s' %(sorted(raw)))

6.斐波那契数列(Fibonacci sequence),从1,1开始,后面每一项等于前面两项之和
def testfunc():
    target=int(input('Please enter the target number: '))
    res=0
    a,b=1,1
    for i in range(target-1):
       a,b=b,a+b
    print('Fibonacci sequence result: %d' %a)


7. 输出 9*9 乘法口诀表。
    def testfunction():
        for i in range(1,10):
            for j in range(1,i+1):
                print('%d*%d=%2ld '%(i,j,i*j))

8.获取当前时间,格式时间打印,和暂停输出

import time   #需要在文件开头添加
def testfunc():
    for i in range(4):
        print(str(int(time.time()))) #当前时间的1970纪元后经过的浮点秒数
        print(time.localtime( time.time() )) #当前时间的一种时间格式
        print(time.strftime('time after shift formation:%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        print(time.asctime( time.localtime(time.time()) )) #当前时间的常见时间格式
        time.sleep(1)

9.有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
def testfunc():
    month=int(input('How many months to breed:'))
    month_1=1
    month_2=0
    month_3=0
    month_elder=0
    for i in range(month):
        month_1,month_2,month_3,month_elder=month_elder+month_3,month_1,month_2,month_elder+month_3
        month_all=month_1+month_2+month_3+month_elder
        print('the %dth month: %d pairs of rabbits'%(i+1,month_all))
        print('One-month-old rabbit:%d'%(month_1))
        print('Two-month-old rabbit:%d'%(month_2))
        print('Three-month-old rabbit%d:'%(month_3))
        print('Adult rabbits:%d'%(month_elder))

10.判断101-200之间有多少个素数,并输出所有素数。
import math
def testfunc():
    for i in range(100,200):
        for j in range(2,int(math.sqrt(i))+1):
            if i%j==0:
                break
        else:
            print("%d is prime" %(i))

11.打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
def testfunc():
    for i in range(100,999):
        s=str(i)
        one=int(s[-1])
        ten=int(s[-2])
        hun=int(s[-3])
        if i == one**3+ten**3+hun**3:
           print("Number of daffodilsi: %d"%(i))

12.利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
def testfunc():
    points=int(input('please enter the points:'))
    if points>=90:
        grade='A'
    elif points<60:
        grade='C'
    else:
        grade='B'
    print('the grade of student is ' + str(grade))

13.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数

读入字符串的时候pthon2.7要用raw_input,python3.7则不必
    string = raw_input("please enter string:")
    alp=0
    num=0
    spa=0
    oth=0
    length=len(string)
    for i in range(length):
        if string[i].isspace():
            spa+=1
        elif string[i].isdigit():
            num+=1
        elif string[i].isalpha():
            alp+=1
        else:
            oth+=1
    print("space: %d" %(spa))
    print("digit: %d" %(num))
    print("alpha: %d" %(alp))
    print("other: %d" %(oth))

14.一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
def testfunc():
    high=200.
    total=100
    for i in range(10):
        high/=2
        total+=high
        print(high/2)
    print("total length%d"%total)

15.两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
def testfunc():
    a=set(['x','y','z'])
    b=set(['x','y','z'])
    c=set(['x','y','z'])
    c-=set(('x','z'))
    a-=set('x')
    print(a)
    print(b)
    print(c)
    for i in a:
        for j in b:
            for k in c:
                if len(set((i,j,k)))==3:
                    print('Table Tennis Matches is a:%s,b:%s,c:%s'%(i,j,k))

16.打印出菱形

使用str.center(width[, fillchar]) 该方法返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。
def draw(num):
    a="*"*(2*(4-num)+1)
    print(a.center(25,' '))
    if num!=1:
        draw(num-1)
        print(a.center(25,' '))

def testfunc():
    draw(4)
 

17.利用递归方法求任意输入数的阶乘
def factorial(n):
    return n*factorial(n-1) if n>1 else 1

def testfunc():
    num=int(input('please enter number for factoring:'))
    print("the factoral value of %d is %d"%(num,factorial(num))) 

18. 给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
print(a[-1])表示取最后一个元素  print(a[:-1])表示除了最后一个取全部  print(a[::-1])表示取从后向前(相反)的元素  print(a[2::-1]) 表示取从下标为2的元素翻转读取
def testfunc():
    a=int(input('Enter a positive integer:'))
    a=str(a)
    print('This is a %d-digit number.'%len(a))
    print("the last element",a[-1])
    print("All except the last",a[:-1]) 
    print("element from the backward direction",a[::-1])
    print("the element from the backward direction from subscript 2",a[2::-1])
    print("From the second element to the last element",a[1:])

19.一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
def testfunc():
    n=raw_input('Enter a number string:')
    a=0
    b=len(n)-1
    flag=True
    while a<b:
        if n[a]!=n[b]:
            print('It is not number of replies')
            flag=False
            break
        a,b=a+1,b-1
    if flag:
        print('It is number of replies')

20. 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母
def testfunc():
    weekT={'h':'thursday',
           'u':'tuesday'}
    weekS={'a':'saturday',
           'u':'sunday'}
    week={'t':weekT,
          's':weekS,
          'm':'monday',
          'w':'wensday',
          'f':'friday'}
    a=week[str(raw_input('please enter the first letter:')).lower()]
    if a==weekT or a==weekS:
        print(a[str(raw_input('please enter the second letter:')).lower()])
    else:
        print(a)


21. 求100以内的素数
用else执行for循环的奖励代码(如果for是正常完结,非break)
def testfunc():
    lo=int(input('MIN:'))
    hi=int(input('MAX:'))
    for i in range(lo,hi+1):
        if i > 1:
            for j in range(2,i):
                if (i % j) == 0:
                    break
            else:
                print(i)

22.输入10个数并进行排序
用append在数组里追加添加
def testfunc():
    raw=[]
    for i in range(10):
        x=int(input('int%d: '%(i)))
        raw.append(x)
    
    for i in range(len(raw)):
        for j in range(i,len(raw)):
            if raw[i]>raw[j]:
                raw[i],raw[j]=raw[j],raw[i]
    print(raw)

23.列表转字符串
注意join的使用
def testfunc():
    L = [1,2,3,4,5]
    print('*'.join(str(n) for n in L))
    print(''.join(str(n) for n in L))

24.求一个3*3矩阵主对角线元素之和
遇到expected a intended block是指格式缩进不对
def testfunc():
    mat=[[1,2,3],[3,4,5],[4,5,6]]
    res=0
    for i in range(len(mat)):
        res+=mat[i][i]
    print(res)
 

25.将一个数组逆序输出
def testfunc():
    list=[1,10,100,1000,10000,100000]
    print('the list is '+" ".join(str(i) for i in list)) 
    print(list)
    list.reverse()
    print('the list after reverse is '+" ".join(str(i) for i in list)) 
    print(list)

26.类的方法与变量
def dummy():
    i=0
    print(i)#输出全是0
    i+=1

class cls:
    i=0
    def dummy(self):
        print(self.i)#依次输出0到9
        self.i+=1

#主函数
if __name__ == '__main__':
    a=cls()
    for i in range(10):
        dummy()
        a.dummy()
 

27.求输入数字的平方,如果平方运算后小于 50 则退出
def testfunc():
    while True:
        try:
            n=float(input('please enter a number:'))
        except:
            print('enter err')
            continue
        dn=n**2
        print("its square is %f"%(dn))
        if dn<50:
            print('its square less than 50, quit!')
            break

28.使用lambda来创建匿名函数
def testfunc():
    Max=lambda x,y:x*(x>=y)+y*(y>x)
    Min=lambda x,y:x*(x<=y)+y*(y<x)

    a=int(input('1:'))
    b=int(input('2:'))

    print(Max(a,b))
    print(Min(a,b))

29.使用 random 模块输出随机数
def testfunc():
    print( random.randint(1,10) )        # 产生 1 到 10 的一个整数型随机数  
    print( random.random() )             # 产生 0 到 1 之间的随机浮点数
    print( random.uniform(1.1,5.4) )     # 产生  1.1 到 5.4 之间的随机浮点数,区间可以不是整数
    print( random.choice('tomorrow') )   # 从序列中随机选取一个元素
    print( random.randrange(1,100,2) )   # 生成从1到100的间隔为2的随机整数

    a=[1,3,5,6,7]                # 将序列a中的元素顺序打乱
    random.shuffle(a)
    print(a)
 

30.位操作,按位与,或,异或,取反,移位
    print("12&8 = "+str(12&8))#测试与
    print("12&8&3 = "+str(12&8&3))#测试与
    print("12|8 = "+str(12|8))#测试或
    print("12|8|3 = "+str(12|8|3))#测试或
    print("31^22 = "+str(31^22))#测试异或
    print("~123 = "+str(~123))#测试非
    a=0o077 #八进制63
    print('the binary of a is '+str(bin(a)))
    print("a is %d"%a)
    a=a>>2
    print("Rightward Shift 2: %d"%a)
    print('the binary of a is '+str(bin(a)))
    a=a<<2
    print("Left Shift 2: %d"%a)
    print('the binary of a is '+str(bin(a)))
    a=a<<2
    print("Left Shift 2: %d"%a)
    print('the binary of a is '+str(bin(a)))
    a=~a
    print("inverse: %d"%a)
    print('the inverse of a is '+str(bin(a)))

31.画图,用canvas.create_oval画圆形
注意Tkinter 在py2和py3中的使用差别
py2 与 py3 中 tkinter 的变化:
  Tkinter        → tkinter
    tkMessageBox    → tkinter.messagebox
    tkColorChooser  → tkinter.colorchooser
    tkFileDialog    → tkinter.filedialog
    tkCommonDialog  → tkinter.commondialog
    tkSimpleDialog  → tkinter.simpledialog
    tkFont          → tkinter.font
    Tkdnd          → tkinter.dnd
    ScrolledText    → tkinter.scrolledtext
    Tix            → tkinter.tix
    ttk            → tkinter.ttk

def testfunc():
    from Tkinter import *   #python3 是tkinter
    canvas=Canvas(width=800,height=600,bg='white') #Canvas画布,整个画布的长宽,背景颜色
    canvas.pack(expand=YES,fill=BOTH)
    k=1
    j=1
    for i in range(6):
        canvas.create_oval(310-k,250-k,310+k,250+k,width=10) #前两位表示图形左上角的位置,后面两个点表示右下角的位置
        k+=j
        j+=10
    mainloop()

32.添加了 Canvas 组件,分别绘制矩形和椭圆
def testfunc():
    from Tkinter import *   #python3 是tkinter
    # 创建窗口
    root = Tk()
    # 创建并添加Canvas
    cv = Canvas(root, background='white')
    cv.pack(fill=BOTH, expand=YES)
    cv.create_rectangle(30, 30, 200, 200,
        outline='red', # 边框颜色
        stipple = 'question', # 填充的位图
        fill="red", # 填充颜色
        width=5 # 边框宽度
        )
    cv.create_oval(240, 30, 330, 200,  #前两位表示图形左上角的位置,后面两个点表示右下角的位置
        outline='yellow', # 边框颜色
        fill='pink', # 填充颜色
        width=4 # 边框宽度
     )
    root.mainloop()
33.查找字符串
str.find(str, beg=0, end=len(string))  如果包含子字符串返回开始的索引值,否则返回-1
def testfunc():
    s1="MSRP msrprequest22044 200 OK\
To-Path: msrp://127.0.0.1:10064/10018014016062116050900343;tcp\
From-Path: msrp://127.0.0.2:5881/10018015016062116051000338;tcp\
Message-ID: 12299053\
-------msrprequest22044$"
    s2='msrp'
    s3='From-Path'
    print(s1.find(s2))
    print(s1.find(s2,30))
    print(s1.find(s2,30,35))
    print(s1.find(s3))


34.输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组
index() 函数用于从列表中找出某个值第一个匹配项的索引位置。list.index(x[, start[, end]]) 
该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。
def testfunc():
    li=[3,2,5,7,8,1,5]
    li[-1],li[li.index(min(li))]=li[li.index(min(li))],li[-1] #最后一个和最小的交换
    m=li[0]
    ind=li.index(max(li))#最大的和最后一个交换
    li[0]=li[ind]
    li[ind]=m
    print(li)

    aList = [123, 'xyz', 'runoob', 'abc']
    print "xyz index position: ", aList.index( 'xyz' )
    print "runoob index position : ", aList.index( 'runoob', 1, 3 )


35.旋转数列 有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
def testfunc():
    #deque和c++中stl的deque相似,是一种双向队列,底层据说也是同样用双链表实现的
    from collections import *
    li=[1,2,3,4,5,6,7,8,9]
    #deque模块是python标准库collections中的一项,它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作。
    deq=deque(li,maxlen=len(li)) 
    print(li)
    deq.rotate(int(input('rotate:'))) #rotate:循环移动,为正全体右移,为负全体左移
    print(list(deq))
    d=deque('12345')
    d.append(6)
    d.append(7)
    d.append(8)
    print(len(d))
    print(d.pop()) #抛出的是’8’
    print(d.pop()) #抛出的是’7’
    de=deque(maxlen=20) #限制deque的长度
    for i in range(30):
         de.append(str(i))
    print(list(de)) #可以发现只有20个项,10开始
 

36.列表排序及连接。
def testfunc():
    a=[2,6,8]
    b=[7,0,4]
    a.extend(b)
    print(a)
    a.sort()
    print(a)

37.编写一个函数,输入n为偶数时,调用函数求1/2+1/4+…+1/n,当输入n为奇数时,调用函数1/1+1/3+…+1/n
def peven(n):
    i = 0
    s = 0.0
    for i in range(2,n + 1,2):
        s += 1.0 / i
    return s
 
def podd(n):
    s = 0.0
    for i in range(1, n + 1,2):
        s += 1.0 / i
    return s
 
def dcall(fp,n):
    s = fp(n)
    return s

#主函数
if __name__ == '__main__':
    n = int(input('input a number: '))
    if n % 2 == 0:
        sum = dcall(peven,n)
    else:
        sum = dcall(podd,n)
    print (sum)

38.找到年龄最大的人,并输出
def testfunc():
    person = {"li":18,"wang":50,"zhang":20,"sun":22}#创建字典方法1
    print(person)
    dictionary = {}
    key1 =['lin','fang','su']
    value1 = ['13','14','15']
    dictionary1 = dict(zip(key1,value1))#创建字典方法2
    print(dictionary1)
    key1 =('lin','fang','su')#改成元祖
    dictionary2 = {key1:value1}#创建字典方法
    print(dictionary2)
    dictionary3 = dict(zhao = '40',qian = '41')#创建字典方法3
    print(dictionary3)
    m = 'li'
    for key in person.keys():
        if person[m] < person[key]:
            m = key
    print ('%s,%d' % (m,person[m]))


39.eval函数的使用,基本用法
Python中的eval()函数eval(expression, globals=None, locals=None)  官方文档中的解释是,将字符串str当成有效的表达式来求值并返回计算结果。globals和locals参数是可选的,如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。
def testfunc():
    n=eval('0o'+str(int(input('八进制输入:'))))
    print(n)
    print(eval('1+2'))
    a = "{1: 'a', 2: 'b'}"
    print(type(a))#type 'str'
    b = eval(a)
    print(type(b)) #type 'dict'
    print(b)
    a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
    print(type(a)) #type 'str'
    b=eval(a)
    print(type(b)) #type 'tuple'
    print(b)
    a=1
    g={'a':20}
    num=eval("a+1",g)
    print(num)

40. eval函数的使用,第二第三参数测试
def g():    
    x = 2    
    y = 2  
    num2 = eval("x+y")    
    print (num2)        #4
    num3 = eval("x+y",globals())
    print (num3)     #2
    num4 = eval("x+y",globals(),locals())    
    print (num4)   #4

if __name__ == '__main__':
    #testfunc();
    #test eval() and locals()
    x = 1
    y = 1
    num1 = eval("x+y")
    print (num1)  #2
    g()

41.连接字符串
def testfunc():
    delimiter = '-'
    mylist = ['Brazil', 'Russia', 'India', 'China']
    print(delimiter.join(mylist))

42.访问类成员,结构体变量传递
if __name__ == '__main__':
    class student:
        x = 0
        c = 0
    def f(stu):
        stu.x = 20
        stu.c = 'c'
    a= student()
    a.x = 3
    a.c = 'a'
    f(a)
    print(a.x,a.c)

43.读取3个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*
def testfunc():
    for i in range(3):
        print('*'*int(input('input a number: ')))

44.某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。
def testfunc():
    n=input('please tell me 4 number: ')
    n = str(n)
    if(4 != int(len(n))):
        print('the length of n is not 4:',str(len(n)))
        return
    a=[]
    for i in range(4):
        a.append((int(n[i])+5)%10)
    a[0],a[3]=a[3],a[0]
    a[1],a[2]=a[2],a[1]
    print ("".join('%s' %s for s in a))

45.计算字符串中子串出现的次数
def testfunc():
    s1='xuebixuebixuebixuebixuebixuebixuebixue'
    s2='xuebi'
    print(s1.count(s2))

46.从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件中保存
def testfunc():
    filename = 'D:\python_test\content.txt'
    fp = open(filename,'w')
    string = raw_input('please input a string:\n')
    string = string.upper()
    fp.write(string)
    fp = open(filename,'r')
    print fp.read()
    fp.close()

47.从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止
def testfunc():
    filename = 'D:\python_test\content.txt'
    fp = open(filename,"w")
    ch = raw_input('please enter a string:\n')
    while ch != '#':
        fp.write(ch)
        #stdout.write(ch)
        ch = raw_input('')
    fp.close()

48.一个猜数游戏,判断一个人反应快慢
def testfunc():
    play_it = raw_input('do you want to play it.(\'y\' or \'n\')')
    while play_it == 'y':
        c = raw_input('input any character to begin the game:\n')
        i = random.randint(0,2**32) % 100
        start = time.clock()
        a = time.time()
        guess = int(raw_input('input your guess:\n'))
        while guess != i:
            if guess > i:
                print 'please input a little smaller'
                guess = int(raw_input('input your guess:\n'))
            else:
                print 'please input a little bigger'
                guess = int(raw_input('input your guess:\n'))
        end = time.clock()
        b = time.time()
        var = (end - start) / 1.0
        print("It took you %d seconds to guess" %(b-a))
        print("Seconds took to guess is "+str(var))
        if var < 15:
            print 'you are very clever!'
        elif var < 25:
            print 'you are normal!'
        else:
            print 'you are stupid!'
        print 'Congradulations'
        print 'The number you guess is %d' % i
        play_it = raw_input('do you want to play it.')

49.Python 之 %s字符串 测试
def testfunc():
    string="hello"
    #%s打印时结果是hello    
    print "string=%s" % string      # output: string=hello    
        
    #%2s意思是字符串长度为2,当原字符串的长度超过2时,按原长度打印,所以%2s的打印结果还是hello    
    print "string=%2s" % string     # output: string=hello    

    #%7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串左侧补空格,    
    #所以%7s的打印结果是  hello    
    print "string=%7s" % string     # output: string=  hello    

    #%-7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串右侧补空格,    
    #所以%-7s的打印结果是  hello    
    print "string=%-7s!" % string     # output: string=hello  !    

    #%.2s意思是截取字符串的前2个字符,所以%.2s的打印结果是he    
    print "string=%.2s" % string    # output: string=he    

    #%.7s意思是截取字符串的前7个字符,当原字符串长度小于7时,即是字符串本身,    
    #所以%.7s的打印结果是hello    
    print "string=%.7s" % string    # output: string=hello    

    #%a.bs这种格式是上面两种格式的综合,首先根据小数点后面的数b截取字符串,    
    #当截取的字符串长度小于a时,还需要在其左侧补空格    
    print "string=%7.2s" % string   # output: string=     he    
    print "string=%2.7s" % string   # output: string=hello    
    print "string=%  .7s" % string  # output: string=     hello    
           
    #还可以用%*.*s来表示精度,两个*的值分别在后面小括号的前两位数值指定    
    print "string=%*.*s" % (7,2,string)      # output: string=     he  

50.Python 之 %d整型 测试
def testfunc():
    num=14    

#%d打印时结果是14    
    print "num=%d" % num            # output: num=14    

#%1d意思是打印结果为1位整数,当整数的位数超过1位时,按整数原值打印,所以%1d的打印结果还是14    
    print "num=%1d" % num           # output: num=14    

#%3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数左侧补空格,所以%3d的打印结果是 14    
    print "num=%3d" % num           # output: num= 14    

#%-3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数右侧补空格,所以%3d的打印结果是14_    
    print "num=%-3d" % num          # output: num=14_    

#%05d意思是打印结果为5位整数,当整数的位数不够5位时,在整数左侧补0,所以%05d的打印结果是00014    
    print "num=%05d" % num          # output: num=00014    

#%.3d小数点后面的3意思是打印结果为3位整数,    
#当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果是014    
    print "num=%.3d" % num          # output: num=014    

#%.0003d小数点后面的0003和3一样,都表示3,意思是打印结果为3位整数,    
#当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果还是014    
    print "num=%.0003d" % num       # output: num=014    

#%5.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,再在左侧补空格,    
#规则就是补0优先,最终的长度选数值较大的那个,所以%5.3d的打印结果还是  014    
    print "num=%5.3d" % num         # output: num=  014    
#%05.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,    
#由于是05,再在左侧补0,最终的长度选数值较大的那个,所以%05.3d的打印结果还是00014    
    print "num=%05.3d" % num        # output: num=00014    

#还可以用%*.*d来表示精度,两个*的值分别在后面小括号的前两位数值指定    
#如下,不过这种方式04就失去补0的功能,只能补空格,只有小数点后面的3才能补0    
    print "num=%*.*d" % (04,3,num)  # output: num= 014
    #print('the bonus is %d'%(bonus))

51.Python 之 %f浮点型 测试
def testfunc():   
    #%a.bf,a表示浮点数的打印长度,b表示浮点数小数点后面的精度    

    #只是%f时表示原值,默认是小数点后5位数    
    print "PI=%f" % math.pi             # output: PI=3.141593    

    #只是%9f时,表示打印长度9位数,小数点也占一位,不够左侧补空格    
    print "PI=%9f" % math.pi            # output: PI=_3.141593    

    #只有.没有后面的数字时,表示去掉小数输出整数,03表示不够3位数左侧补0    
    print "PI=%03.f" % math.pi          # output: PI=003    

    #%6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够左侧补空格    
    print "PI=%6.3f" % math.pi          # output: PI=_3.142    

    #%-6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够右侧补空格    
    print "PI=%-6.3f" % math.pi         # output: PI=3.142_    

    #还可以用%*.*f来表示精度,两个*的值分别在后面小括号的前两位数值指定    
    #如下,不过这种方式06就失去补0的功能,只能补空格    
    print "PI=%*.*f" % (06,3,math.pi)   # output: PI=_3.142  
    #print('the bonus is %d'%(bonus))

52. 异常处理测试
import os
def testfunc(): 
    print os.getcwd()
    os.chdir("D:\\python_test\\")
    print os.getcwd()
    try:
        fh = open("testfile.txt", "r")# change r to w ,then it will succ
        fh.write("this is a test file")
    except IOError:# BaseException or Exception is also ok
        print "Error: not find the file"
    else:
        print "write file succ"
        fh.close()
    finally:
        print "test try end"

53.列表转为字典
def testfunc(): 
    i = ['a', 'b']
    l = [1, 2]
    print dict([i,l]) 

54.有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。
def testfunc(): 
    print os.getcwd()
    os.chdir("D:\\python_test\\")
    print os.getcwd()
    fp = open('test1.txt')
    a = fp.read()
    fp.close()

    fp = open('test2.txt')
    b = fp.read()
    fp.close()

    fp = open('test3.txt','w')
    l = list(a + b)
    print l
    l.sort()
    print l
    s = ' '
    s = s.join(l)
    print s
    fp.write(s)
    fp.close()

55.列表的增减以及打印
def testfunc(): 
    testList=[10086,'china moble',[1,2,4,5]]      #新建列表
    print len(testList)     #访问列表长度 
    print testList[1:]      #打印第2项到列表结尾  
    testList.append('i\'m new here!')    #向列表添加元素,‘需要转义    
  
    print len(testList)  
    print testList[-1]      #打印列表的最后一个元素  
    print testList.pop(1)  #弹出列表的最后一个元素 
    print len(testList)  
    print testList  

    matrix = [[1, 2, 3],  
    [4, 5, 6],  
    [7, 8, 9]]  
    print matrix  
    print matrix[1] #打印矩阵的第二行 
    col2 = [row[1] for row in matrix]#带你矩阵的第二列
    print col2  
    col2even = [row[1] for row in matrix if  row[1] % 2 == 0]#打印矩阵的第二列里的偶数  
    print col2even

56.正则表达式练习 re.match函数
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
re.match(pattern, string, flags=0)
正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:
def testfunc(): 
    print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配,(0, 3)
    print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配 ,None
    line = "Cats are smarter than dogs"
    matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)#re.M 多行匹配,影响 ^ 和 $ ,re.I使匹配对大小写不敏感
    print matchObj
    if matchObj:
        print "matchObj.group() : ", matchObj.group() #Cats are smarter than dogs
        print "matchObj.group(1) : ", matchObj.group(1) #Cats
        print "matchObj.group(2) : ", matchObj.group(2) #smarter
    else:
        print "No match!!"

57.正则表达式练习,re.search函数
re.search 扫描整个字符串并返回第一个成功的匹配。
函数语法:
re.search(pattern, string, flags=0)
def testfunc(): 
    print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配,(0, 3)
    print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配,(11, 14)

    line = "Cats are smarter than dogs";

    searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

    if searchObj:
        print "searchObj.group() : ", searchObj.group() #Cats are smarter than dogs
        print "searchObj.group(1) : ", searchObj.group(1) #Cats
        print "searchObj.group(2) : ", searchObj.group(2) #smarter
    else:
        print "Nothing found!!"

58.re.match与re.search的对比测试
def testfunc(): 
    line = "Cats are smarter than dogs";
    matchObj = re.match( r'dogs', line, re.M|re.I)
    if matchObj:
        print "match --> matchObj.group() : ", matchObj.group() #No match!!
    else:
       print "No match!!"

    matchObj = re.search( r'dogs', line, re.M|re.I)
    if matchObj:
       print "search --> searchObj.group() : ", matchObj.group() #search --> searchObj.group() :  dogs
    else:
       print "No match!!"

59.用re.sub检索和替换字符串
re.sub(pattern, repl, string, count=0, flags=0)
def testfunc(): 
    phone = "2004-959-559 # 这是一个国外电话号码"
 
    # 删除字符串中的 Python注释 
    num = re.sub(r'#.*$', "", phone)
    print "phone number is : ", num #phone number is : 2004-959-559 

    # 删除非数字(-)的字符串 
    num = re.sub(r'\D', "", phone)
    print "phone number is: ", num #phone number is : 2004959559

    # 将所有的9都替换成1 
    num = re.sub(r'9', "1", phone)
    print "phone number is: ", num #phone number is : 2004-151-559=1 # 这是一个国外电话号码

    # 将前两个的9都替换成1 
    num = re.sub(r'9', "1", phone,2)
    print "phone number is: ", num #phone number is : 2004-151-559 # 这是一个国外电话号码

60.用re.sub检索和替换字符串,repl 参数是一个函数
re.sub(pattern, repl, string, count=0, flags=0)
def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)
 
def testfunc(): 
    s = 'A23G4HFD567'
    print(re.sub('(?P<value>\d+)', double, s)) #A46G8HFD1134

61.re.compile 函数使用
compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。
re.compile(pattern[, flags])
flags : 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:
re.I 忽略大小写
re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
re.M 多行模式
re.S 即为 . 并且包括换行符在内的任意字符(. 不包括换行符)
re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
re.X 为了增加可读性,忽略空格和 # 后面的注释
def testfunc(): 
    pattern = re.compile(r'\d+')                    # 用于匹配至少一个数字
    m = pattern.match('one12twothree34four')        # 查找头部,没有匹配
    print m #None
    m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配
    print m #None
    m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
    print m                                         # 返回一个 Match 对象 #<_sre.SRE_Match object at 0x10a42aac0>
    print m.group(0)   # 可省略 0  #'12'
    print m.start(0)   # 可省略 0  #3
    print m.end(0)     # 可省略 0  #5
    print m.span(0)    # 可省略 0  #(3, 5)

62.re.compile 函数使用,忽略大小写测试
def testfunc(): 
    pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I)   # re.I 表示忽略大小写
    m = pattern.match('Hello World Wide Web')
    print m                               # 匹配成功,返回一个 Match 对象 #<_sre.SRE_Match object at 0x10bea83e8>
    print m.group(0)                            # 返回匹配成功的整个子串 #'Hello World'
    print m.span(0)                             # 返回匹配成功的整个子串的索引 #(0, 11)
    print m.group(1)                            # 返回第一个分组匹配成功的子串 #'Hello'
    print m.span(1)                             # 返回第一个分组匹配成功的子串的索引 #(0, 5)
    print m.group(2)                            # 返回第二个分组匹配成功的子串 #'World'
    print m.span(2)                             # 返回第二个分组匹配成功的子串 #(6, 11)
    print m.groups()                            # 等价于 (m.group(1), m.group(2), ...)

63.findall 正则表达式匹配所有子串,并返回一个列表
在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
注意: match 和 search 是匹配一次 findall 匹配所有。
语法格式为:
findall(string[, pos[, endpos]])
参数:
string : 待匹配的字符串。
pos : 可选参数,指定字符串的起始位置,默认为 0。
endpos : 可选参数,指定字符串的结束位置,默认为字符串的长度。
def testfunc(): 
    pattern = re.compile(r'\d+')   # 查找数字
    result1 = pattern.findall('baidu 123 google 456') #['123', '456']
    result2 = pattern.findall('baidu123google456', 0, 10) #['123']

    print(result1)
    print(result2)

64.re.finditer 迭代器返回
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。
re.finditer(pattern, string, flags=0)
def testfunc(): 
    it = re.finditer(r"\d+","12a32bc43jf3") 
    for match in it: 
        print (match.group() )
#12
#32
#43
#3

65.re.split分隔
split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下:
re.split(pattern, string[, maxsplit=0, flags=0])
参数:
pattern    匹配的正则表达式
string    要匹配的字符串。
maxsplit    分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。
flags    标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志
def testfunc(): 
    print re.split('\W+', 'runoob, runoob, runoob.')
#['runoob', 'runoob', 'runoob', '']
    print re.split('(\W+)', '123 runoob, runoob, runoob.') 
#['', ' ', 'runoob', ', ', 'runoob', ', ', 'runoob', '.', '']
    print re.split('\W+', ' runoob, runoob, runoob.', 1) #只分割一次
#['', 'runoob, runoob, runoob.']
    print re.split('a*', 'hello world')   # 对于一个找不到匹配的字符串而言,split 不会对其作出分割
#['hello world']

66.File对象的属性测试
一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。
以下是和file对象相关的所有属性的列表:
file.closed    返回true如果文件已被关闭,否则返回false。
file.mode    返回被打开文件的访问模式。
file.name    返回文件的名称。
file.softspace    如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
write()方法不会在字符串的结尾添加换行符('\n'):
fileObject.write(string)

read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
fileObject.read([count])

tell()方法告诉你文件内的当前位置, 换句话说,下一次的读写会发生在文件开头这么多字节之后。
seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。
如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。
def testfunc(): 
    os.chdir("D:\\python_test\\")
    fo = open("foo.txt", "w")
    print "文件名: ", fo.name  #foo.txt
    print "是否已关闭 : ", fo.closed  #False
    print "访问模式 : ", fo.mode   #w
    print "末尾是否强制加空格 : ", fo.softspace  #0
    fo.write("this is a test file")
    fo = open("foo.txt", "r+")
    str = fo.read(10)
    print "读取的字符串是 : ", str #this is a
    print "文件名: ", fo.closed  #True
    position = fo.tell()
    print "当前文件位置 : ", position   #10
    # 把指针再次重新定位
    position = fo.seek(-2, 1)
    str = fo.read()
    print "重新读取字符串 : ", str   #a test file
    # 把指针再次重新定位
    position = fo.seek(0, 0)
    str = fo.read()
    print "重新读取字符串 : ", str   #this is a test file
    # 把指针再次重新定位
    position = fo.seek(2, 0)
    str = fo.read()
    print "重新读取字符串 : ", str   #is is a test file
    # 把指针再次重新定位
    position = fo.seek(-2, 2)
    str = fo.read()
    print "重新读取字符串 : ", str    #le
    fo.close()
    os.rename( "foo.txt", "fooo.txt" )
    os.remove("fooo.txt")
    os.mkdir("newdir")
    os.chdir("newdir")
    print os.getcwd()  #D:\python_test\mkdir

67.用套接字进行客户端服务端测试,最简单,服务端发送一个消息给客户端,客户端收到并打印
服务端
import socket               # 导入 socket 模块
def testfunc(): 
 
    s = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口
    s.bind((host, port))        # 绑定端口

    s.listen(5)                 # 等待客户端连接
    while True:
        c,addr = s.accept()     # 建立客户端连接
        print 'connect address:', addr
        c.send('Hi,I am Xiaoxiangzai')
        c.close()                # 关闭连接

客户端
def testfunc(): 
    s = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口号
 
    s.connect((host, port))
    print s.recv(1024)
    s.close()

68.用套接字进行客户端服务端测试,jack和bob可以进行多回合的聊天

服务端(bob):
def testfunc(): 
    import socket               # 导入 socket 模块
 
    s = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口
    s.bind((host, port))        # 绑定端口

    s.listen(5)                 # 等待客户端连接
    while True:
        conn,addr = s.accept()     # 建立客户端连接
        print 'connect address:', addr
        while True:
            # 获取从客户端发送的数据
            # 一次获取不超过1k的数据
            data = conn.recv(1024)
            print 'from jack:', data
            # 在终端输入要返回的消息
            re_data = raw_input('bob:')
            # 返回给客户端数据
            conn.send(re_data)
        conn.close()                # 关闭连接

客户端(jack):
def testfunc(): 
    client = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口号
    client.connect((host, port))
    while True:
        re_data = raw_input('jack:')
        client.send(re_data)
        data = client.recv(1024)
        print 'from bob:', data
    client.close()

69. python 面向对象类的测试,员工信息修改
class Employee:
   '所有员工的基类'
   empCount = 0
 
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount
 
   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

def testfunc(): 
    #"创建 Employee 类的第一个对象"
    emp1 = Employee("Smart Zhang", 20000)
    #"创建 Employee 类的第二个对象"
    emp2 = Employee("Middle Wang", 15000)
    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount
    emp1.age = 30  # 添加一个 'age' 属性
    print "the age of first employee %d" %emp1.age
    emp1.age = 29  # 修改 'age' 属性
    print "the age of first employee %d" %emp1.age
    setattr(emp1, 'age', 28)
    print "the age of first employee %d" %emp1.age
    print 'Whether exists age of emp1:',hasattr(emp1, 'age')
    print 'Get the age of emp1:',getattr(emp1, 'age') 
    del emp1.age  # 删除 'age' 属性
    print 'Whether exists age of emp1:',hasattr(emp1, 'age')
    setattr(emp1, 'age', 27) # 添加属性 'age' 值为 27
    print "the age of first employee %d" %emp1.age
    delattr(emp1, 'age')
    print 'Whether exists age of emp1:',hasattr(emp1, 'age')

70.python 面向对象类的测试,员工信息修改,测试内置属性
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
class Employee:
   'doc content'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount
 
   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

def testfunc(): 
    print "Employee.__doc__:", Employee.__doc__
    print "Employee.__name__:", Employee.__name__
    print "Employee.__module__:", Employee.__module__
    print "Employee.__bases__:", Employee.__bases__
    print "Employee.__dict__:", Employee.__dict__

输出:
Employee.__doc__: doc content
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x10a939c80>, 'empCount': 0, 'displayEmployee': <function displayEmployee at 0x10a93caa0>, '__doc__': '\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb', '__init__': <function __init__ at 0x10a939578>}

71.python对象销毁(垃圾回收)
Python 使用了引用计数这一简单技术来跟踪和回收垃圾。
在 Python 内部记录着所有使用中的对象各有多少引用。
一个内部跟踪变量,称为一个引用计数器。
当对象被创建时, 就创建了一个引用计数, 当这个对象不再需要时, 也就是说, 这个对象的引用计数变为0 时, 它被垃圾回收。但是回收不是"立即"的, 由解释器在适当的时机,将垃圾对象占用的内存空间回收。
析构函数 __del__ ,__del__在对象销毁的时候被调用,当对象不再被使用时,__del__方法运行:
class Point:
   def __init__( self, x=0, y=0):
      self.x = x
      self.y = y
   def __del__(self):
      class_name = self.__class__.__name__
      print class_name, "destory"

def testfunc(): 
    pt1 = Point()
    pt2 = pt1
    pt3 = pt1
    print id(pt1), id(pt2), id(pt3) # 打印对象的id
    del pt1
    del pt2
    del pt3
以上实例运行结果如下:
3083401324 3083401324 3083401324
Point destory

72.类的继承测试
在python中继承中的一些特点:
1、如果在子类中需要父类的构造方法就需要显示的调用父类的构造方法,或者不重写父类的构造方法。详细说明可查看:python 子类继承父类构造函数说明。
2、在调用基类的方法时,需要加上基类的类名前缀,且需要带上 self 参数变量。区别在于类中调用普通函数时并不需要带上 self 参数
3、Python 总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。
class Parent:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"
 
   def parentMethod(self):
      print '调用父类方法'
 
   def setAttr(self, attr):
      Parent.parentAttr = attr
 
   def getAttr(self):
      print "父类属性 :", Parent.parentAttr
 
class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"
 
   def childMethod(self):
      print '调用子类方法'

def testfunc(): 
    c = Child()          # 实例化子类
    c.childMethod()      # 调用子类的方法
    c.parentMethod()     # 调用父类方法
    c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
    c.getAttr()          # 再次调用父类的方法 - 获取属性值

73.如果父类方法的功能不能满足你的需求,可以在子类重写父类的方法
class Parent:        # 定义父类
   def myMethod(self):
      print '调用父类方法'
 
class Child(Parent): # 定义子类
   def myMethod(self):
      print '调用子类方法'
def testfunc(): 
    c = Child()          # 子类实例
    c.myMethod()         # 子类调用重写方法

执行以上代码输出结果如下:
调用子类方法

下表列出了一些通用的功能,可以在自己的类重写:
序号    方法, 描述 & 简单的调用
1    __init__ ( self [,args...] )
构造函数
简单的调用方法: obj = className(args)
2    __del__( self )
析构方法, 删除一个对象
简单的调用方法 : del obj
3    __repr__( self )
转化为供解释器读取的形式
简单的调用方法 : repr(obj)
4    __str__( self )
用于将值转化为适于人阅读的形式
简单的调用方法 : str(obj)
5    __cmp__ ( self, x )
对象比较
简单的调用方法 : cmp(obj, x)

74.运算符重载
class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b
 
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
 
def testfunc(): 
    v1 = Vector(2,10)
    v2 = Vector(5,-2)
    print v1 + v2

以上代码执行结果如下所示:
Vector(7,8)

75.类属性与方法测试
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods
class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print self.__secretCount

def testfunc(): 
    counter = JustCounter()
    counter.count()
    counter.count()
    print counter.publicCount
    #print counter.__secretCount  # 报错,实例不能访问私有变量

运行结果
1
2
2
Traceback (most recent call last):
  File "test.py", line 17, in <module>
    print counter.__secretCount  # 报错,实例不能访问私有变量
AttributeError: JustCounter instance has no attribute '__secretCount'

以下为python3.8上测试通过的练习题
76.

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值