python—模組導入和類

1.查詢模組:按目錄依次查找需要導入的模組,模組目錄一般在:/usr/lib64/python2.7

In [2]: sys.path  Out[2]:  ['',  '/usr/bin',  '/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg',  '/usr/lib64/python27.zip',   '/usr/lib64/python2.7',  '/usr/lib64/python2.7/plat-linux2',  '/usr/lib64/python2.7/lib-tk',  '/usr/lib64/python2.7/lib-old',  '/usr/lib64/python2.7/lib-dynload',  '/usr/lib64/python2.7/site-packages',  '/usr/lib/python2.7/site-packages',  '/usr/lib/python2.7/site-packages/python_memcached-1.58-py2.7.egg',  '/usr/lib/python2.7/site-packages/IPython/extensions',  '/root/.ipython']

2.自定義模組目錄

方法一:sys.path.append(),一般加在目錄列表最後

In [3]: sys.path.append("/root/python/")  In [4]: sys.path  Out[4]:  ['',  '/usr/bin',  '/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg',  '/usr/lib64/python27.zip',  '/usr/lib64/python2.7',  '/usr/lib64/python2.7/plat-linux2',  '/usr/lib64/python2.7/lib-tk',  '/usr/lib64/python2.7/lib-old',  '/usr/lib64/python2.7/lib-dynload',  '/usr/lib64/python2.7/site-packages',  '/usr/lib/python2.7/site-packages',  '/usr/lib/python2.7/site-packages/python_memcached-1.58-py2.7.egg',  '/usr/lib/python2.7/site-packages/IPython/extensions',  '/root/.ipython',   '/root/python/']

方法二:修改環境變數,一般加在目錄列表前面

vim /root/.bashrc   # 加入 export PYTHONPATH=/root/python  source /root/.bashrc  # 刷新

例子:統計一個文件,行數、單詞數、字元數(和wc命令相同效果)

說明:為了避免使用split切割之後,最後多出一個空字元串,而使用count()

#/usr/bin/env python  def count(s):      char = len(s)      words = len(s.split())      lines = s.count("n")      print lines,words,char    file1 = open("/etc/passwd","r")  s = file1.read()  count(s)

3.腳本形式,導入模組,腳本名字不能是數字,會產生一個編譯文件

例子:

#!/usr/bin/env python  import wc

說明:目錄下生產編譯文件:wc.pyc

4.py和wc.py的__name__內置變數不一樣,前者是wc,或者是__main__,修改wc.py,執行自己時,輸出自己的結果,被調用時,執行不顯示源結果:

wc.py:

#/usr/bin/env python  def count(s):      char = len(s)      words = len(s.split())      lines = s.count("n")      print lines,words,char    if __name__ == "__main__":       file1 = open("/etc/passwd","r")      s = file1.read()      count(s)

test.py:

#!/usr/bin/env python  import wc  s = open("/root/python/10.py","r").read()  wc.count(s)

5.包的形式,導入模組

四種導入方法:在包目錄dir下創建一個__init__.py空文件

方法一:

from dir import wc  wc.count("abc")

方法二:

import dir.wc  dir.wc.count("abc")

方法三:

from dir.wc import count  count("abc")

方法四:別名

from dir.wc import count as count  count("abc")

6.面向對象編程:python、java、C++;面向過程編程:C、函數式編程、shell

類的(靜態)屬性:(人類的五官,理解為變數)

類的(動態)方法:(人類吃穿住行,理解為一個函數)

對象:類的實例化,之後才能有屬性和方法

7.類的創建

類的方法中,至少有一個參數self

調用屬性時,不帶括弧

調用方法時,使用括弧;方法調用屬性時,至少有一個self參數

屬性調用其他方法:類名.屬性名

例子:

class People():      color = "yellow"      def think(self):                # 加上self表示是類的方法,不加則表示函數          self.color = "black"    # 加上self表示是類的屬性          print ("My color is %s "% (self.color))    ren = People()         # 類的實例化  print ren.color          # 類的屬性外部調用  ren.think()               # 類的方法外部調用,如加上print,則多一個默認return值none

運行結果:

yellow

My color is black

8.私有屬性在定義的類中的內部函數中被調用

例子:

class People():      color = "yellow"      __age = 27      def think(self):          self.color = "black"          print self.__age                         # 內部函數調用類的私有屬性,外部函數不能直接調用          print ("My color is %s "% (self.color))  ren = People()  print ren.color  ren.think()

9.外部調用私有屬性(格式:實例化名._類名屬性名),一般只是測試用

例子:

class People():      color = "yellow"      __age = 27      def think(self):          self.color = "black"          print self.__age          print ("My color is %s "% (self.color))    ren = People()  print ren.color  ren.think()  print ren._People__age          # 外部調用私有屬性

10.類的方法

公有方法:內部和外部都可以調用

私有方法:內部函數調用

動態方法:classmethod()函數處理,沒有被調用的類的其他參數不會載入進記憶體中

靜態方法:

方法的定義和函數一樣,但是需要把self作為第一個參數,如果還是有其他參數,繼續加上;類實例化之後,採用「類名.方法名()」調用

例子1:私有方法調用

class People():      color = "yellow"      __age = 27      def __think(self):          self.color = "black"          print self.__age          print ("My color is %s "% (self.color))      def test(self):          self.__think()           # 類的私有方法調用  ren = People()  ren.test()                        # 類的私有方法調用

例子2:動態方法調用

class People():      color = "yellow"      __age = 27      def __think(self):          self.color = "black"          print self.__age          print ("My color is %s "% (self.color))      def test(self):          print ("Testing...")       cm = classmethod(test)        # 動態方法定義    ren = People()  ren.cm()                                   # 動態方法調用

例子3:靜態方法調用:

類函數不帶self參數,該函數使用staticmethod()函數處理(如果不處理,缺少self,,調用時會報錯),載入關於這個類的所有東西

class People():      color = "yellow"      __age = 27      def __think(self):          self.color = "black"          print self.__age          print ("My color is %s "% (self.color))      def test():                                 #  內部函數,不帶self          print ("Testing...")          #print People.color              # 因為沒有self,不能調用該類的屬性          cm = staticmethod(test)          # 靜態方法定義  ren = People()  ren.cm()                                     # 靜態方法調用

例子4:加裝飾器,只對下面的一個函數起作用,就可以使用類的方法調用了

class People():      color = "yellow"      __age = 27      def __think(self):          self.color = "black"          print self.__age          print ("My color is %s "% (self.color))            @classmethod                 # 加裝飾器,可以通過類來調用      def test(self):                   # 動態方法,帶self          print ("Testing...")            @staticmethod               # 加裝飾器      def test1():                     # 靜態方法,不帶self          print ("Testing1..")    ren = People()  People.test()                 # 類的方法調用  People.test1()               # 類的方法調用

11.定義內部類

方法一:

class People():      color = "yellow"      __age = 27      class Chinese(object):     # 定義內部類          country = "I am chinese"  hzp = People.Chinese()      # 外部類.內部類實例化  print hzp.country                # 實例化後,調用內部類的屬性

方法二:

class People():      color = "yellow"      __age = 27      class Chinese(object):          country = "I am chinese"  hzp = People()                  # 先外部類實例化  hzp2 = hzp.Chinese()       # 再內部類實例化  print hzp2.country

方法三:

class People():      color = "yellow"      __age = 27      class Chinese(object):          country = "I am chinese"  print People.Chinese.country                # 類的方法  print People.Chinese().country             # 相當於People.Chinese()實例化,最後調用屬性

12.構造函數和析構函數

構造函數用於初始化類的內部狀態,提供的函數是__init__(),不給出則會提供默認方法

析構函數用於釋放佔用的資源,提供的函數是__del__(),不給出則會提供默認方法

1)__str__(self):只能使用return,不能使用print,無需調用和列印,會自動調用

例子1:

class People():      color = "yellow"      __age = 27      class Chinese(object):          country = "I am chinese"      def __str__(self):                # 定義__str__(self)          return("This is a test")    # return返回結果,不能使用print    ren = People()  print ren                                # 類實例化後,自動調用

運行結果:

This is a test

2)__init__():初始化值,不需調用,實例化後,自動執行,也可以傳值

例子2:

class People():      color = "yellow"      __age = 27      class Chinese(object):          country = "I am chinese"      def __str__(self):          return("This is a test")      def __init__(self):          self.color = "black"    ren = People()  print ren.color           # 實例化後,變成「black」  print People.color     # 類直接調用,color值不變

運行結果:

black

yellow

3)__del__():在腳本最後執行,釋放資源;如果沒有析構函數釋放資源,也沒關係,python通過gc模組,實現垃圾回收機制

例子3:

class People():      def __init__(self):         # 構造函數,打開文件          print("Initing...")          self.fd = open("/etc/hosts","r"):      def __del__(self):       # 析構函數,關掉文件          print("End")          self.fd.close()  ren = People()  ren

運行結果:

Initing…

End