[Python筆記]Python學習筆記四

來源:互聯網
上載者:User

標籤:main   模組名   sys   span   if判斷   ror   變數   訪問   官網   

模組

在Python中,一個.py檔案就是一個模組(Module)

使用模組的好處就是大大提高代碼的可維護性,並且可以被其他地方引用。

同時可以避免函數名和變數名的衝突。

Package(包) 每個包目錄下面必須有一個 __init__.py檔案

這個檔案可以是空的,這個檔案對應模組名就是目前的目錄名即包名

 

模組的使用

Python內建了很多模組

#!/usr/bin/env python# -*- coding:utf-8 -*-# 編寫一個屬於自己的模組
# 檔案的第一個字串被視為模組的文檔注釋‘a test module‘
# 模組作者
__author__ = ‘JoyJoe‘import sysdef test():
# sys.argv使用列表來儲存命令列的所有參數,第一個元素永遠都是檔案名稱 args
= sys.argv if len(args) == 1: print ‘Hello world!‘ elif len(args)==2: print ‘Hello, %s‘%args[1] else: print ‘Too many arguments!‘
# 在命令列運行檔案時,Python解譯器會把變數__name__置為 __main__
# 這樣如果在其他地方匯入該模組時if判斷將會失敗
# 一般用於運行測試if __name__ == ‘__main__‘: test()

 

匯入模組時可以設定別名

try:    import cStringIO as StringIOexcept ImportError:    import StringIO
try:    import jsonexcept ImportError:    import simplejson as json

 

範圍

在Python中,規定__xxx__這樣的變數為特殊變數,如__name__, __author__, __doc__等

Python同樣在類或模組中沒有函數存取權限修飾符

 

第三方模組安裝

使用官方推薦的pip 也可以使用easy_install

Python非常強大的一個處理映像的工具庫Python Imaging Library (在官網上註冊名PIL)

pip install PIL

import Imageim = Image.open(‘test.png‘)print im.format, im.size, im.modeim.thumbnail((200, 100))im.save(‘thumb.jpg‘, ‘JPEG‘)

常用第三方庫:

MySQL-python

numpy

Jinja2

模組的載入過程:Python解譯器會搜尋目前的目錄下所有已經安裝的內建模組和第三方模組,搜尋路徑存放在sys模組的path變數中

import sysprint sys.path

Python提供了 __future__ 模組,把下一個新版本的特性匯入到目前的版本中

為了適應Python3.x中的字串表示方法,在Py2.7中通過unicode_literals來使用新文法

# still running on Python2.7from __future__ import unicode_literalsprint ‘\‘xxx\‘ is unicode?‘, isinstance(‘xxx‘, unicode)print ‘u\‘xxx\‘ is unicode?‘, isinstance(u‘xxx‘, unicode)print ‘\‘xxx\‘ is str?‘, isinstance(‘xxx‘, str)print ‘b\‘xxx\‘ is str?‘, isinstance(b‘xxx‘, str)

Python3中, 所有字元都視為unicode 如果需要使用二進位字串則必須添加首碼b

Python3中,所有除法都是精確除法

 

from __future__ import division

 

[Python筆記]Python學習筆記四

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.