Python函數的設計規范
1、Python函數設計時具備耦合性和聚合性
1)、耦合性:
(1).盡可能通過參數接受輸入,以及通過return產生輸出以保證函數的獨立性;
(2).盡量減少使用全局變量進行函數間通信;
(3).不要在函數中直接修改可變類型的參數;
(4).避免直接改變定義在另外一個模塊中的變量;
2)、聚合性:
(1).每個函數都應該有一個單一的、目的統一的目標;
(2).每個函數的功能都應該相對簡單;
2、Python函數在腳本中應用示例
例1: 將/etc/passwd文件中的每一行都分隔為一個列表
[root@test0528]# vim test1.py #!/usr/bin/python27 # importre filename ='/etc/passwd' f1 =open(filename,'r') l1 =f1.readlines() bash =[] for i inl1: bash.append(i) defgenList(x): y = 0 x = len(bash) while y <= x: yield bash[y] y += 1 g1 =genList(bash) count =0 whilecount < len(bash): gg=g1.next() linelist = gg.split(':') print linelist count += 1 f1.close() [root@test0528]# ./test1.py ['root','x', '0', '0', 'root', '/root', '/bin/bash\n'] ['bin','x', '1', '1', 'bin', '/bin', '/sbin/nologin\n'] ['daemon','x', '2', '2', 'daemon', '/sbin', '/sbin/nologin\n'] ...... ['nginx','x', '496', '493', 'nginx user', '/var/cache/nginx','/sbin/nologin\n'] ['mysql','x', '27', '27', 'MySQL Server', '/var/lib/mysql','/bin/bash\n'] ['redis','x', '495', '492', 'Redis Database Server', '/var/lib/redis','/sbin/nologin\n']
例2: 將任意文件按用戶指定的分隔符把每一行都分隔為一個列表
[root@test0528]# vim test2.py #!/usr/bin/python27 # importre #print"PLease input filename:" #filename= raw_input() filename =str(raw_input("PLease input filename: ")) f1 =open(filename,'r') l1 =f1.readlines() #print"PLease input separator:" #separator= raw_input() separator= str(raw_input("PLease input separator: ")) bash =[] for i inl1: bash.append(i) defgenList(x): y = 0 x = len(bash) while y <= x: yield bash[y] y += 1 g1 =genList(bash) count =0 whilecount < len(bash): gg=g1.next() linelist = gg.split(separator) print linelist count += 1 f1.close() [root@test0528]# ./test2.py PLeaseinput filename: /etc/passwd PLeaseinput separator: : ['root','x', '0', '0', 'root', '/root', '/bin/bash\n'] ['bin','x', '1', '1', 'bin', '/bin', '/sbin/nologin\n'] ['daemon','x', '2', '2', 'daemon', '/sbin', '/sbin/nologin\n'] ... ['nginx','x', '496', '493', 'nginx user', '/var/cache/nginx','/sbin/nologin\n'] ['mysql','x', '27', '27', 'MySQL Server', '/var/lib/mysql','/bin/bash\n'] ['redis','x', '495', '492', 'Redis Database Server', '/var/lib/redis','/sbin/nologin\n'] 例3:用折疊的方式(reduce)求階乘 [root@test0528]# vim test3.py #!/usr/bin/python27 # getn! num =int(raw_input('please nput a number:')) num +=1 list =range(1,num) deffunc(m,n): return m*n x =reduce(func,list) printx [root@test0528]# ./test3.py pleasenput a number:4 24
以上這篇對Python函數設計規范詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
