Python心得基礎篇【8】面向對象相關

其餘相關

1、isinstance(obj, cls)html

 檢查是否obj是不是類 cls 的對象python

1 class Foo(object):
2     pass
3  
4 obj = Foo()
5  
6 isinstance(obj, Foo)

2、issubclass(sub, super)web

檢查sub類是不是 super 類的派生類sql

1 class Foo(object):
2     pass
3  
4 class Bar(Foo):
5     pass
6  
7 issubclass(Bar, Foo)

3、異常處理數據庫

一、異常基礎編程

在編程過程當中爲了增長友好性,在程序出現bug時通常不會將錯誤信息顯示給用戶,而是現實一個提示的頁面,通俗來講就是不讓用戶看見大黃頁!!!設計模式

1 try:
2     pass
3 except Exception,ex:
4     pass

 需求:將用戶輸入的兩個數字相加併發

 1 while True:
 2     num1 = raw_input('num1:')
 3     num2 = raw_input('num2:')
 4     try:
 5         num1 = int(num1)
 6         num2 = int(num2)
 7         result = num1 + num2
 8     except Exception, e:
 9         print '出現異常,信息以下:'
10         print e
View Code

二、異常種類框架

python中的異常種類很是多,每一個異常專門用於處理某一項異常!!!ide

萬能異常 在python的異常中,有一個萬能異常:Exception,他能夠捕獲任意異常

接下來你可能要問了,既然有這個萬能異常,其餘異常是否是就能夠忽略了!

答:固然不是,對於特殊處理或提醒的異常須要先定義,最後定義Exception來確保程序正常運行。

1 s1 = 'hello'
2 try:
3     int(s1)
4 except KeyError,e:
5     print '鍵錯誤'
6 except IndexError,e:
7     print '索引錯誤'
8 except Exception, e:
9     print '錯誤'

4、反射

python中的反射功能是由如下四個內置函數提供:hasattr、getattr、setattr、delattr,改四個函數分別用於對對象內部執行:檢查是否含有某成員、獲取成員、設置成員、刪除成員。

反射:根據字符串形式去某個模塊中尋找東西getattr
根據字符串形式去某個模塊中判斷東西是否存在hasattr
setattr 去某個模塊設置東西,包括變量、函數
delattr 內存中刪除 不影響原文件 上面模塊也是對象
 1 class Foo(object):
 2  
 3     def __init__(self):
 4         self.name = 'wupeiqi'
 5  
 6     def func(self):
 7         return 'func'
 8  
 9 obj = Foo()
10  
11 # #### 檢查是否含有成員 ####
12 hasattr(obj, 'name')
13 hasattr(obj, 'func')
14  
15 # #### 獲取成員 ####
16 getattr(obj, 'name')
17 getattr(obj, 'func')
18  
19 # #### 設置成員 ####
20 setattr(obj, 'age', 18)
21 setattr(obj, 'show', lambda num: num + 1)
22  
23 # #### 刪除成員 ####
24 delattr(obj, 'name')
25 delattr(obj, 'func')
View Code

詳細解析:

當咱們要訪問一個對象的成員時,應該是這樣操做:

 1 class Foo(object):
 2  
 3     def __init__(self):
 4         self.name = 'alex'
 5  
 6     def func(self):
 7         return 'func'
 8  
 9 obj = Foo()
10  
11 # 訪問字段
12 obj.name
13 # 執行方法
14 obj.func()

那麼問題來了?
a、上述訪問對象成員的 name 和 func 是什麼? 
答:是變量名
b、obj.xxx 是什麼意思? 
答:obj.xxx 表示去obj中或類中尋找變量名 xxx,並獲取對應內存地址中的內容。
c、需求:請使用其餘方式獲取obj對象中的name變量指向內存中的值 「alex」
class Foo(object):
 
    def __init__(self):
        self.name = 'alex'
 
# 不容許使用 obj.name
obj = Foo()

答:有兩種方式,以下:

class Foo(object):

    def __init__(self):
        self.name = 'alex'

    def func(self):
        return 'func'

# 不容許使用 obj.name
obj = Foo()

print obj.__dict__['name']

方式一
class Foo(object):

    def __init__(self):
        self.name = 'alex'

    def func(self):
        return 'func'

# 不容許使用 obj.name
obj = Foo()

print getattr(obj, 'name')

方式二

d、比較三種訪問方式

  • obj.name
  • obj.__dict__['name']
  • getattr(obj, 'name')

答:第一種和其餘種比,...
      第二種和第三種比,...

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3 from wsgiref.simple_server import make_server
 4 
 5 class Handler(object):
 6 
 7     def index(self):
 8         return 'index'
 9 
10     def news(self):
11         return 'news'
12 
13 
14 def RunServer(environ, start_response):
15     start_response('200 OK', [('Content-Type', 'text/html')])
16     url = environ['PATH_INFO']
17     temp = url.split('/')[1]
18     obj = Handler()
19     is_exist = hasattr(obj, temp)
20     if is_exist:
21         func = getattr(obj, temp)
22         ret = func()
23         return ret
24     else:
25         return '404 not found'
26 
27 if __name__ == '__main__':
28     httpd = make_server('', 8001, RunServer)
29     print "Serving HTTP on port 8000..."
30     httpd.serve_forever()
31 
32 Web框架實例
web框架實例

結論:反射是經過字符串的形式操做對象相關的成員。一切事物都是對象!!!

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

import sys


def s1():
    print 's1'


def s2():
    print 's2'


this_module = sys.modules[__name__]

hasattr(this_module, 's1')
getattr(this_module, 's2')

反射當前模塊成員
View Code

設計模式

1、單例模式

單例,顧名思義單個實例。

學習單例以前,首先來回顧下面向對象的內容:

python的面向對象由兩個很是重要的兩個「東西」組成:類、實例

面向對象場景一:

如:建立三個遊戲人物,分別是:

  • 蒼井井,女,18,初始戰鬥力1000
  • 東尼木木,男,20,初始戰鬥力1800
  • 波多多,女,19,初始戰鬥力2500
# #####################  定義類  #####################
class Person:

    def __init__(self, na, gen, age, fig):
        self.name = na
        self.gender = gen
        self.age = age
        self.fight =fig

    def grassland(self):
        """註釋:草叢戰鬥,消耗200戰鬥力"""

        self.fight = self.fight - 200

# #####################  建立實例  #####################

cang = Person('蒼井井', '', 18, 1000)    # 建立蒼井井角色
dong = Person('東尼木木', '', 20, 1800)  # 建立東尼木木角色
bo = Person('波多多', '', 19, 2500)      # 建立波多多角色

面向對象場景二:

如:建立對數據庫操做的公共類

# #### 定義類 ####

class DbHelper(object):

    def __init__(self):
        self.hostname = '1.1.1.1'
        self.port = 3306
        self.password = 'pwd'
        self.username = 'root'

    def fetch(self):
        # 鏈接數據庫
        # 拼接sql語句
        # 操做
        pass

    def create(self):
        # 鏈接數據庫
        # 拼接sql語句
        # 操做
        pass

    def remove(self):
        # 鏈接數據庫
        # 拼接sql語句
        # 操做
        pass

    def modify(self):
        # 鏈接數據庫
        # 拼接sql語句
        # 操做
        pass

# #### 操做類 ####

db = DbHelper()
db.create()

實例:結合場景二實現Web應用程序

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3 from wsgiref.simple_server import make_server
 4 
 5 
 6 class DbHelper(object):
 7 
 8     def __init__(self):
 9         self.hostname = '1.1.1.1'
10         self.port = 3306
11         self.password = 'pwd'
12         self.username = 'root'
13 
14     def fetch(self):
15         # 鏈接數據庫
16         # 拼接sql語句
17         # 操做
18         return 'fetch'
19 
20     def create(self):
21         # 鏈接數據庫
22         # 拼接sql語句
23         # 操做
24         return 'create'
25 
26     def remove(self):
27         # 鏈接數據庫
28         # 拼接sql語句
29         # 操做
30         return 'remove'
31 
32     def modify(self):
33         # 鏈接數據庫
34         # 拼接sql語句
35         # 操做
36         return 'modify'
37 
38 
39 class Handler(object):
40 
41     def index(self):
42         # 建立對象
43         db = DbHelper()
44         db.fetch()
45         return 'index'
46 
47     def news(self):
48         return 'news'
49 
50 
51 def RunServer(environ, start_response):
52     start_response('200 OK', [('Content-Type', 'text/html')])
53     url = environ['PATH_INFO']
54     temp = url.split('/')[1]
55     obj = Handler()
56     is_exist = hasattr(obj, temp)
57     if is_exist:
58         func = getattr(obj, temp)
59         ret = func()
60         return ret
61     else:
62         return '404 not found'
63 
64 if __name__ == '__main__':
65     httpd = make_server('', 8001, RunServer)
66     print "Serving HTTP on port 8001..."
67     httpd.serve_forever()
68 
69 Web應用程序實例
View Code

對於上述實例,每一個請求到來,都須要在內存裏建立一個實例,再經過該實例執行指定的方法。

那麼問題來了...若是併發量大的話,內存裏就會存在很是多功能上如出一轍的對象。存在這些對象確定會消耗內存,對於這些功能相同的對象能夠在內存中僅建立一個,須要時都去調用,也是極好的!!!

鐺鐺 鐺鐺 鐺鐺鐺鐺鐺,單例模式出馬,單例模式用來保證內存中僅存在一個實例!!!

經過面向對象的特性,構造出單例模式:

# ########### 單例類定義 ###########
class Foo(object):
 
    __instance = None
 
    @staticmethod
    def singleton():
        if Foo.__instance:
            return Foo.__instance
        else:
            Foo.__instance = Foo()
            return Foo.__instance
 
# ########### 獲取實例 ###########
obj = Foo.singleton()

對於Python單例模式,建立對象時不能再直接使用:obj = Foo(),而應該調用特殊的方法:obj = Foo.singleton() 。

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3 from wsgiref.simple_server import make_server
 4 
 5 # ########### 單例類定義 ###########
 6 class DbHelper(object):
 7 
 8     __instance = None
 9 
10     def __init__(self):
11         self.hostname = '1.1.1.1'
12         self.port = 3306
13         self.password = 'pwd'
14         self.username = 'root'
15 
16     @staticmethod
17     def singleton():
18         if DbHelper.__instance:
19             return DbHelper.__instance
20         else:
21             DbHelper.__instance = DbHelper()
22             return DbHelper.__instance
23 
24     def fetch(self):
25         # 鏈接數據庫
26         # 拼接sql語句
27         # 操做
28         pass
29 
30     def create(self):
31         # 鏈接數據庫
32         # 拼接sql語句
33         # 操做
34         pass
35 
36     def remove(self):
37         # 鏈接數據庫
38         # 拼接sql語句
39         # 操做
40         pass
41 
42     def modify(self):
43         # 鏈接數據庫
44         # 拼接sql語句
45         # 操做
46         pass
47 
48 
49 class Handler(object):
50 
51     def index(self):
52         obj =  DbHelper.singleton()
53         print id(single)
54         obj.create()
55         return 'index'
56 
57     def news(self):
58         return 'news'
59 
60 
61 def RunServer(environ, start_response):
62     start_response('200 OK', [('Content-Type', 'text/html')])
63     url = environ['PATH_INFO']
64     temp = url.split('/')[1]
65     obj = Handler()
66     is_exist = hasattr(obj, temp)
67     if is_exist:
68         func = getattr(obj, temp)
69         ret = func()
70         return ret
71     else:
72         return '404 not found'
73 
74 if __name__ == '__main__':
75     httpd = make_server('', 8001, RunServer)
76     print "Serving HTTP on port 8001..."
77     httpd.serve_forever()
78 
79 Web應用實例-單例模式
View Code

總結:單利模式存在的目的是保證當前內存中僅存在單個實例,避免內存浪費!!!

相關文章
相關標籤/搜索