Python的模块化编程
生活随笔
收集整理的這篇文章主要介紹了
Python的模块化编程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們首先以一個例子來介紹模塊化編程的應用場景,有這樣一個名為requirements.py的python3文件,其中兩個函數的作用是分別以不同的順序來打印一個字符串:
def example1():a = 'hello world!'print (a)print (a[::-1])def example2():b = 'hello again!'print (b)print (b[::-1])if __name__ == '__main__':example1()example2()其執行結果如下所示:
[dechin@dechin-manjaro decorator]$ python3 requirements.py hello world! !dlrow olleh hello again! !niaga olleh在兩個函數中都使用到了同樣的打印功能,這時候我們可以考慮,是不是可以將這兩個打印語句封裝為一個函數呢,這樣不就可以重復利用了?這就是模塊化編程思維的雛形,讓我們先對樣例代碼進行模塊化的改造:
def rprint(para):print (para)print (para[::-1])def example1():a = 'hello world!'rprint(a)def example2():b = 'hello again!'rprint (b)if __name__ == '__main__':example1()example2()這里我們將兩個打印語句的功能實現封裝進了rprint的函數,執行結果如下:
[dechin@dechin-manjaro decorator]$ python3 requirements.py hello world! !dlrow olleh hello again! !niaga olleh結果當然還是與模塊化之前一致的。
結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
https://www.bilibili.com/video/BV1LL4y1h7ny?share_source=copy_web
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
https://www.bilibili.com/video/BV1QZ4y1N7YA?share_source=copy_web
總結
以上是生活随笔為你收集整理的Python的模块化编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3函数可变输入参量
- 下一篇: Python 中关于 round 函数的