zoukankan      html  css  js  c++  java
  • Python心得基础篇【8】面向对象相关

    其他相关

    一、isinstance(obj, cls)

     检查是否obj是否是类 cls 的对象

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

    二、issubclass(sub, super)

    检查sub类是否是 super 类的派生类

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

    三、异常处理

    1、异常基础

    在编程过程中为了增加友好性,在程序出现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

    2、异常种类

    python中的异常种类非常多,每个异常专门用于处理某一项异常!!!

    万能异常 在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 '错误'

    四、反射

    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

    设计模式

    一、单例模式

    单例,顾名思义单个实例。

    学习单例之前,首先来回顾下面向对象的内容:

    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

    总结:单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费!!!

  • 相关阅读:
    CSS实现底部固定
    ES6新特性--多行文本
    DataTable转实体
    jQuery插件开发
    页面可编辑
    clearfix--清除浮动
    前端日历控件推荐
    图片Base64编码
    第八周学习进度博客
    人月神话多后感01
  • 原文地址:https://www.cnblogs.com/hank-lkj/p/8506399.html
Copyright © 2011-2022 走看看