日常python學習-5

2018.3.12

1.模塊

看廖雪峯的一個模板:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Michael Liao'

import sys

def test():
    args = sys.argv
    if len(args)==1:
        print('Hello, world!')
    elif len(args)==2:
        print('Hello, %s!' % args[1])
    else:
        print('Too many arguments!')

if __name__=='__main__':
    test()
  • 第一二行已經解釋過了,一個是以Python3去運行腳本,另一個是規定編碼方式.
  • 模塊代碼的第一個字符串被解釋成此模塊的註釋.對應的就是’a test module’
  • author變量是爲了說明作者,開源的時候讓別人知道這個模塊是誰寫的

這三個步驟就是Python的標準模塊文件的寫法.之後是模塊的代碼內容

2.sys module
import sys

引入sys模塊,此模塊中有一個argv參數,是一個list. argv記錄了命令行傳入的參數:

python3 hello.py

此時argv的值就是['hello.py']

python3 hello.py world

此時argv的值就是['hello.py','world']


補充說明第一個module的代碼:

命令行運行hello模塊文件時Python解釋器把一個特殊變量name置爲main,而如果在其他地方導入該hello模塊時,if判斷將失敗,因此,這種if測試可以讓一個模塊通過命令行運行時執行一些額外的代碼,最常見的就是運行測試

if __name__=='__main__':
    test()

這裏就比較像main()函數,當然作用是不一樣的.

命令行運行腳本hello.py:

wh@ukula:~/python$ python3 hello.py python
Hello,python!

只是import一下腳本:

>>> import hello.py
>>> hello.test()
Hello, world!
3.作用域
def _private_1(name):
    return 'Hello, %s' % name

def _private_2(name):
    return 'Hi, %s' % name

def greeting(name):
    if len(name) > 3:
        return _private_1(name)
    else:
        return _private_2(name)

函數名,變量名 如果以_開頭,意思是定義爲私有的函數,不希望被外部引用.但是Python沒有一個強制的約束,因此只是一個約定的習慣.比如greeting函數中,把兩個private都封裝起來了,外部只要管greeting的調用方法,內部的兩個private都不要被外部調用爲好.

外部不需要調用的函數全部定義爲private,外部需要用的函數才定義爲public

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章