天天看點

python基礎5

子產品

什麼是子產品:所有以.py結尾的都可以認為是一個子產品

例:編寫一個.py結尾的檔案實作四則運算,再用另一個.py檔案去導入

###cacl.py檔案,實作四則運算###

#!/usr/bin/env python

#coding:utf-8

from __future__ import division###__future__該子產品中含有python3.x的方法,導入就可以使用這些方法###

def add(x,y):

    return x + y

def sub(x,y):

    return x -y

def multi(x,y):

    return x*y

def divi(x,y):

    return x/y

###hello.py檔案,導入cacl.py檔案###

import cacl

print cacl.add(2,5)

print cacl.divi(5,2)

執行結果:

7

2.5

####導入子產品的三種方法###

1 import cacl###導入cacl子產品,使用時一定要加上cacl

例:

2 from   cacl   import add###導入cacl子產品中的add方法,使用時不用加cacl,可以直接使用###

from   cacl   import add

print add(2,5)

3 from cacl import add    as myadd###如果目前py代碼包含add方法,但仍然想要使用cacl中的add方法,隻需将cacl中的add方法重命名即可###

from cacl import add    as myadd

    return  x+y+1

print myadd(2,5)

8

###導入子產品的靈活應用####

1 導入子產品的多個方法

from cacl import sub,multi###導入加法,減法###

print sub(2,5)

print multi(2,5)

####路徑搜尋,搜尋路徑###

添加一路徑,讓路徑搜尋時導入相應的自定義子產品

路徑搜尋:重點是在搜尋

搜尋路徑:重點是在路徑,即sys.path顯示出來的路徑

搜尋路徑:當你寫了一個.py檔案,想要在任何時刻的的都可以導入該子產品,則需将該.py檔案加入搜尋路徑中

In [3]: sys.path

Out[3]:

['',

 '/usr/bin',

 '/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/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython']

In [4]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day05/')

In [5]: sys.path

Out[5]:

 '/home/kiosk/.ipython',

 '/home/kiosk/PycharmProjects/pythonbasic/day05/']

In [6]: import decorate###加入搜尋路徑後,則可以導入###

hello....

1.00119495392

hello1....

None

hello2....

2.00213503838

hello3....

In [7]: sys.path.pop()

Out[7]: '/home/kiosk/PycharmProjects/pythonbasic/day05/'###一旦彈出,搜尋路徑中沒有該路徑時,就無法導入###

In [9]: sys.path

Out[9]:

In [10]: import decorate

---------------------------------------------------------------------------

ImportError                               Traceback (most recent call last)

<ipython-input-10-96bbe2666044> in <module>()

----> 1 import decorate

ImportError: No module named decorate

###在day05下有一個hello.py檔案,day06下也有一個hello.py檔案,則是讀取第一次導入的内容####

In [11]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day05/')

In [14]: import hello

In [15]: hello.hello1()

hello1.....inday05###day05下hello.py檔案的内容###

In [16]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day06/')###将day06也加入搜尋路徑###

In [17]: import hello

In [18]: hello.hello1()

hello1.....inday05###顯示的仍是day05的内容####

In [19]: sys.path

Out[19]:

 '/home/kiosk/PycharmProjects/pythonbasic/day05/',

 '/home/kiosk/PycharmProjects/pythonbasic/day06/']

In [20]: sys.path.pop()

Out[20]: '/home/kiosk/PycharmProjects/pythonbasic/day06/'

In [21]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day06/')###就算将day06加到最前面,讀取的仍然是day05的内容###

In [22]: import hello

In [23]: hello.hello1()

hello1.....inday05

####在還沒有導入子產品時,導入相同名字的子產品,則,哪個路徑在前,就先讀取哪個,之後就算更改路徑,仍然讀取最初的子產品####

In [2]: sys.path

Out[2]:

In [3]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day06/')

In [4]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day06/')

['/home/kiosk/PycharmProjects/pythonbasic/day06/',

 '',

In [6]: import hello

In [7]: hello.hello1()###讀取day06的子產品的内容###

hello1......in day06

In [8]: sys.path.pop()###彈出day05###

Out[8]: '/home/kiosk/PycharmProjects/pythonbasic/day05/'

In [9]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day05/')###将day05的路徑加到最前面###

In [10]: sys.path

Out[10]:

['/home/kiosk/PycharmProjects/pythonbasic/day05/',

 '/home/kiosk/PycharmProjects/pythonbasic/day06/',

In [11]: import hello###導入hello子產品###

In [12]: hello.hello1()###讀取的仍然是day06下的内容###

####建立包###

import test.cacl    as cacl

print cacl.sub(2,5)

####若是隻導入test包,則需要在__init__.py檔案裡導入子產品###

儲存包的一些資訊,其實是在解釋執行test包裡面的__init__.py檔案

###類class###

程式設計:

面向過程

面向對象

面向函數

class Animals(object)###定義一個類,關鍵字class,類的名稱的第一個字母一定要大寫###

class Animals(object):###定義類###

    cn = 'china'           ###類變量###

    def __init__(self,name,age):###構造函數,後面跟你要傳遞的參數

        self.name = name###self就是執行個體化的變量名,此時,self指的是haha,self.name是執行個體化屬性,靜态屬性

        self.age = age

    def eating(self):###方法,與函數唯一的差別時self,動态屬性###

        print "%s is eating..."%self.name

    def drink(self):

        print "%s is drinking..."%self.name

haha = Animals("fentiao",5)###執行個體化###

haha.eating()

haha.drink()

執行結果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

Process finished with exit code 0

定義一個類變量和在構造函數__init__()内寫入參數的差別,每次執行個體化的時候,都會執行構造函數,是以,若是執行次數很多的時候,構造函數裡的參數就也執行很多次,是以,定義一個類變量會更友善

若是想要傳遞的參數不想要改變,可以加雙下劃線

###可以改變###

class Animals(object):

    cn = 'china'            ###類變量###

    def __init__(self,name,age,gender):

        self.name = name

        self.gender = gender

    def eating(self):

fentiao = Animals("fentiao",5,'male')

fentiao.eating()

fentiao.drink()

print fentiao.gender,fentiao.name

fentiao.gender = "female"

print fentiao.gender

###不可以改變###

        self.__gender = gender###以雙下劃線開頭的變量是私有變量,在類外不可以通路,因為python編譯器會将雙下劃線開頭的變量進行更改,是以要列印雙下劃線開頭的變量會報錯(因為已經發生了改變,找不到)###

print fentiao.__gender###列印不出,會報錯###

想要列印,在類裡再添加一個列印私有變量的方法:

        self.__gender = gender

    def got_gender(self):

        return self.__gender

fentiao.__gender = "female"

print fentiao.__gender

print fentiao.got_gender()

female

male###會發現沒有改變###

###私有方法###

        self.__hello()

    def __hello(self):###定義私有方法###

        print "hello..."

print fentiao.__hello()###無法調用,會報錯###

hello...

male

Traceback (most recent call last):

  File "/home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py", line 84, in <module>

    print fentiao.__hello()

AttributeError: 'Animals' object has no attribute '__hello'

###若是有不想被人通路的方法,則可以把它定義成私有方法###

面向對象的特性:

1 封裝性:私有方法和私有屬性

2 繼承:繼承父類的方法和屬性

3 多态

###多态###

class Cat(Animals):

        print '%s eating fish...'%(self.name)

class Dog(Animals):

        print "%s eating gutou......"%(self.name)

a1 = Animals('animals1',2)

a1.eating()

c1 = Cat('cat1',5)

c1.eating()

d1 = Dog('dog1',4)

d1.eating()

animals1 is eating...

cat1 eating fish...

dog1 eating gutou......

###析構函數###

    def __del__(self):

        print "that's all,game over"

that's all,game over

###或者####

del(a1)

del(c1)

del(d1)

######Animals.__init__(self,name,age)####

    def __init__(self,name,age,color):

        Animals.__init__(self,name,age)

        self.color = color

    def info(self):

        print '''

                cat info

    name:%s

    age:%d

    color:%s

        '''%(self.name,self.age,self.color)

c1 = Cat('cat1',5,'black')

c1.info()

    name:cat1

    age:5

    color:black

#####super(Cat,self).__init__(name,age)####

        # Animals.__init__(self,name,age)

        super(Cat,self).__init__(name,age)

####兩個類之間建立聯系,繼承多個類####

class Realtion(object):

    def make_firends(self,obj):

        print "%s is %s friends"%(self.name,obj.name)

class Cat(Animals,Realtion):

class Dog(Animals,Realtion):

     def eating(self):

         print "%s eating gutou......"%(self.name)

d1 = Dog("dog1",5)

c1.make_firends(d1)

cat1 is dog1 friends

####繼承政策###

廣度優先政策(效率高)python3

深度優先政策:一直找父類的方法,如果沒有找到相應的方法,再去找和c在同一層的類

本文轉自blueclo51CTO部落格,原文連結: http://blog.51cto.com/12774272/1947897,如需轉載請自行聯系原作者