面向对象、查看socketserver源代码执行过程、反射 、异常处理、单例模式

面向对象基础

 1、面向对象不是所有情况都适用

2、面向对象编程

  •   定义类
      class 类名:
                    def  方法1(self,bb)
                    pass

  • 根据类创建对象
    适用对象去执行类中方法

 

 1 class oldboy: #创建类oldboy
 2     def fetch (self, backend):  #定义方法
 3         print()
 4         
 5     def add_record (self, backend, record):#定义方法
 6         pass
 7     
 8 obj = oldboy() #根据类创建对象
 9 obj.fetch() #使用对象去执行类中的方法
10 obj.add_record()

 

 

封装

 1 class oldboy: #创建类oldboy
 2     def fetch (self):  #定义方法
 3         print(self.backend )
 4 
 5     def add_record (self, record):#定义方法
 6         print(self.backend )
 7 
 8 obj1 = oldboy() #根据类创建对象
 9 obj1.backend = "www.Freechen.com" #封装到obj1
10 obj1.fetch()
11 
12 obj2 = oldboy() #根据类创建对象
13 obj2.backend = "www.oldboy.com" #封装到obj2
14 obj2.fetch()

构造方法:  __init__

  类+括号 ----》 自动执行类中的 __init__方法:创建了一个类

  在__init__方法中执行具体的封装的操作

  __init__ 有一个特殊的名字:构造方法

  初始化  

   __del__ 解释器销毁对象的时候自动调用,特殊名称:析构方法。

========================结果==========================

封装:

  使用场景:当同一类型的方法具有相同参数时,直接封装到对象即可。

  使用场景:当类当做模板,创建多个对象,(对象内封装的数据可以不一样)

class foo:
    def __init__(self): #构造方法
        print("init")

obj = foo() #默认执行__init__方法


class foo:
    def __init__(self,bk): #构造方法
        self.name = "alex" #封装
        self.favor = bk  #封装

obj1 = foo("xx") #默认执行__init__方法
r = obj1.name
r2 = obj1.favor
print(r,r2)
class oldboy: #创建类oldboy
    def __init__(self,backend):
        self.name = backend #普通字段
        
    def fetch (self):  #定义方法
        print(self.backend )
        
    def add_record (self, record):#定义方法
        print(self.backend )
        
obj1 = oldboy("alex") #根据类创建对象
ret = obj1.name
print(ret)

 继承:

1、派生类可以继承基类中所有的功能

2、派生类和基类同时存在相同的方法时,优先找派生类。

3、可继承多个类。优先级是:自己----左边----右边

 1 class Animals:
 2     def  chi(self):
 3         print(self.name + "")
 4 
 5     def he(self):
 6         print(self.name+"")
 7 
 8 class Dog(Animals): #继承Animals,Dog是Animals的子类,也叫派生类。Animals 是Dog的父类,也叫基类。
 9     def __init__(self, name):
10         self.name = name
11 
12     def jiao(self):
13         print(self.name + "")
14 alex = Dog("李杰")
15 alex.chi()
16 alex.he()
17 alex.jiao()

 多继承优先级:python3.5

 

多态:

  多种形态

面向对象有三大特性:封装、继承、多态。python支持多继承,其他语言不可以。

接口:Python不存在接口

 

一、面向对象进阶

  成员

    通过类访问的有:静态字段

    通过对象访问:普通字段,类的方法。
  成员修饰符

      出了自己谁也不好使

      私有

  面向对象一些常用特殊方法 __init__ __call__ __delitm__ __dict__  __iter__

    ___metaclass__  __new__

二、异常处理

    try :

      xxx

    except Execption as e :

      print(e)

    try :

      xxx

    except Execption as e :

      xxx

    else:

      xxx

    finally:  

      xxx

三、单例模式

继承:

 1 class A:
 2     def bar(self):
 3         self.f1()
 4     def f1(self):
 5         print("A")
 6 class B(A):
 7     def f1(self):
 8         print("B")
 9 class C:
10     def f1(self):
11         print("C")
12 class D(C,B):
13     def f1(self):
14         print("D")
15 dd = D()
16 dd.bar()

 

 

 

 

 派生类执行基类的构造方法:》

 1 class Annimal:
 2     def __init__(self):
 3         print("Aninimal的构造方法")
 4         self.ty = "动物"
 5 
 6 class Cat(Annimal):
 7     def __init__(self):
 8         print("Cat的构造方法")
 9         self.n = ""
10         #执行父类的构造的两种方法,推荐使用super
11         super (Cat, self).__init__()  #第一种方法
12         Annimal.__init__(self) #第二种方法       
13 c = Cat()
14 print(c.__dict__)

查看socketserver源代码执行过程

以字符串的形式去对象、模块中操作成员。
 1 #反射
 2 #以字符串的形式去对象、模块中操作成员。
 3 #反射:类,只能找类里的成员。
 4 #反射:对象,即可找对象,也可以找类的成员。
 5 class Foo:
 6     def __init__(self,name):
 7         self.name = name
 8     def show(self):
 9         print("show")
10 obj = Foo("free")
11 #对象中找
12 r = hasattr(obj,"name")
13 print(r)
14 r = hasattr(obj,"show")
15 print(r)
16 r = hasattr(obj,"show")
17 print(r)

 

 利用反射导入模块、查找类、创建对象、查找对象中的字段

静态字段,在类中:将对象中存在多份一样的内容,放在类中,即静态字段
 1 class Provice:
 2     #静态字段,在类中:将对象中存在多份一样的内容,放在类中,即静态字段
 3     country = "China"
 4     def __init__(self,name):
 5         #普通字段,在对象中
 6         self.name = name
 7     #普通方法,类中
 8     def show(self):
 9         print("show")
10 hebei = Provice("河北")
11 henan = Provice("河南")

静态字段、静态方法,用类来调用

 1 class Provice:
 2     #静态字段,在类中:将对象中存在多份一样的内容,放在类中,即静态字段
 3     country = "China"
 4     def __init__(self,name):
 5         #普通字段,在对象中
 6         self.name = name
 7     #普通方法,类中
 8     def show(self):
 9         print("show")
10     #静态方法
11     @staticmethod
12     def xo():
13         print("xo")
14 
15 print (Provice.country)
16 Provice.xo()

类方法:

 1 class Provice:
 2     #静态字段,在类中:将对象中存在多份一样的内容,放在类中,即静态字段
 3     country = "China"
 4     def __init__(self,name):
 5         #普通字段,在对象中
 6         self.name = name
 7     #普通方法,类中
 8     def show(self):
 9         print("show")
10     #类方法,必须有一个参数,
11     @classmethod
12     def xxoo(cls):
13         print("xxoo")
14     #静态方法
15     @staticmethod
16     def xo():
17         print("xo")
18 
19 Provice.xo()
20 Provice.xxoo()

类的特性:

#特性,访问时将方法伪造成一种字段
class Provice:
  
    @property
    def end(self):
        temp = "%s sb"%self.name
        return temp

obj = Provice("Free")
print( obj.end)

 给特性方法,设置值

 1 class Provice:
 2     #静态字段,在类中:将对象中存在多份一样的内容,放在类中,即静态字段
 3     country = "China"
 4     def __init__(self,name):
 5         #普通字段,在对象中
 6         self.name = name
 7     #普通方法,类中
 8     def show(self):
 9         print("show")
10     #类方法,必须有一个参数,
11     @classmethod
12     def xxoo(cls):
13         print("xxoo")
14     #静态方法
15     @staticmethod
16     def xo():
17         print("xo")
18     def start(self):
19         temp = "%s sb"%self.name
20         return temp
21     #特性,访问时将方法伪造成一种字段
22     @property
23     def end(self):
24         temp = "%s sb"%self.name
25         return temp
26     @end.setter
27     def end(self,value):
28         print(value)
29         self.name = value
30 obj = Provice("Alex")
31 print(obj.end)
32 obj.end = "123"
33 print(obj.end)

 

 

#__成员修饰符,只有内部成员才可以访问它,私有的只有自己可以访问,子类也不可以访问。
 1 class Foo:
 2     xo = "xo"
 3     __ox = "ox" #__成员修饰符,只有内部成员才可以访问它
 4 
 5     def f1(self):
 6         print("F1")
 7         print(Foo.__ox) #内部访问私有静态字段
 8 obj = Foo()
 9 print(Foo.xo)
10 # print(Foo.__ox)
11 obj.f1()

成员修饰符:公有、私有

 

__call__

1 class Foo:
2     def __init__(self):
3         print("init")
4 
5     def __call__(self, *args, **kwargs):
6         print("call")
7 r = Foo() 
8 r()#调用__call__
9 Foo()()#调用__call__

__getitem__方法

 1 class Foo:
 2     def __init__(self):
 3         print("init")
 4 
 5     def __call__(self, *args, **kwargs):
 6         print("call")
 7 
 8     def  __getitem__(self, item):
 9         print(item)
10 r = Foo()
11 r()#调用__call__
12 Foo()()#调用__call__
13 r["k1"]  #中括号执行__getitem__方法。
r = Foo()       #执行__init__方法
r() #执行__call__方法
r["k1"] #执行__getitem__方法
r["k1"] =123 #执行__setitem__方法
del r["k2"] #执行__delitm__方法

 


 1 class Foo:
 2     '''
 3         我是类的注释
 4     '''
 5     def __init__(self):
 6         print("init")
 7 
 8     def __call__(self, *args, **kwargs):
 9         print("call")
10 
11     def  __getitem__(self, item):
12         print(item)
13 obj = Foo()
14 print(obj.__dict__)
15 print(Foo.__dict__)

基本异常处理:

1 inp = input("Please:")
2 try:
3     num = int(inp)
4     print(num)
5 except  Exception as e:
6     print("数据类型有误")
1 inp = input("Please:")
2 try:
3     num = int(inp)
4     print(num)
5 except ValueError as e: #捕捉值错误,捕捉到之后停止执行,没有捕捉到,继续往下执行。
6     print("值错误")
7 except  Exception as e: #捕捉所有的错误
8     print("数据类型有误")

 主动触发异常

1 try:
2     print("123")
3     raise Exception("出错了") # 主动触发异常
4 except Exception as e:
5     print(e)

其他异常结构

 

 __str__方法
1 class Foo:
2     def __init__(self,arg):
3         self.xo = arg
4 
5     def __str__(self):
6         return self.xo
7 
8 obj = Foo('出错了……')
9 print(obj)

断言

assert  1==1  assert 条件。条件成立往下执行,条件不成立报错。

单例模式

GoF设计模式

大话设计模式

 

设计模式一:单例模式:只有一个实例:静态方法+静态字段。

所有的实例中封装的内容相同时,用单例模式。

====================应用========================

创建Web站点并应用单例模式

 1 #python 2.7
 2 
 3 from wsgiref.simple_server import make_server
 4 
 5 def RunServer(environ,start_response):
 6     start_response(status='200 OK', headers=[('Content-Type', 'text/html')])
 7     url = environ['PATH_INFO']
 8 
 9 
10     return "Oldboy1"
11 
12 
13 if __name__ == '__main__':
14     httpd = make_server('',8000,RunServer)
15     print ("Serving HTTP on prot 8000....")
16     httpd.serve_forever()

 

 

 



posted @ 2019-06-22 09:17  Freechen0  阅读(117)  评论(0)    收藏  举报