首页 > 代码库 > python学习道路(day8note)(抽象类,类的方法,异常处理,socket编程)

python学习道路(day8note)(抽象类,类的方法,异常处理,socket编程)

1.#面向对象
#抽象接口 === 抽象类
#就是架构师给你一个架子,你们去写,如果满足不了直接报错
 1 #python2
 2 print("python2---抽象类".center(20,#))
 3 import abc    #需要在python2中测试,如果直接运行会报错
 4 #因为没有调用send方法
 5 class Alert(object):
 6     ‘‘‘报警基类‘‘‘
 7     __metaclass__ = abc.ABCMeta
 8     @abc.abstractmethod
 9     def send(self):   #特指了 子类必须实现send方法
10         ‘‘‘报警消息发送接口‘‘‘
11         pass
12 class MailAlert(Alert):  #报错函数
13     pass
14 # class MailAlert(Alert):  #正确函数
15 #     def send(self,msg):
16 #         print("-----right---",msg)
17 m = MailAlert()
18 m.send()
19 #m.send(‘hello‘)
20 
21 
22 print("python3---抽象类".center(20,#))
23 class Alert(object):
24     ‘‘‘报警基类‘‘‘
25 
26     def send(self):   #特指了 子类必须实现send方法
27         ‘‘‘报警消息发送接口‘‘‘
28         raise NotImplementedError  #主动报错
29 # class MailAlert(Alert):  #报错函数
30 #     pass
31 class MailAlert(Alert):  #正确函数
32     def send(self):
33         print("-----right---")
34 m = MailAlert()
35 m.send()

 

2.静态方法

 1 ):
 2     def __init__(self,name):
 3         self.name = name
 4     def eat(self):
 5         print("%s is eating...." % self.name)
 6 p = person("alex")
 7 p.eat()
 8 
 9 print("转为静态方法".center(20,#))
10 #为了解决实例化占用内存,但是到时候会需要考虑一下是不是需要真的真么多实例
11 #静态方法就是不需要实例化
12 class person(object):
13     def __init__(self,name):
14         self.name = name
15     @staticmethod
16     def eat(name,food):#静态方法不能访问公有属性,也不能访问实例
17         print("%s is eating...." % name,food)
18 # p = person("alex") #不需要实例了
19 person.eat("alex","shit")

 

3.类方法

 1 print("类方法".center(20,#))
 2 class person(object):
 3     name = "rain"
 4     def __init__(self,name):
 5         self.name = name
 6     @classmethod  #类方法
 7     def walk(self): #类方法只能反问类的公有属性不能访问实力属性
 8         print("%s is walking.." % self.name)
 9 p = person("alex")
10 p.walk()
11 #所以打印出来的是rain在walk

 

4.属性方法

 1 print("属性方法".center(20,#))
 2 class person(object):
 3     name = "rain"
 4     def __init__(self,name):
 5         self.name = name
 6     @property  #属性方法的作用是把一个方法变成一个静态属性
 7     def talk(self):
 8         print("%s is talking.." % self.name)
 9 
10     @talk.setter
11     def talk(self,msg):
12         print("set msg:",msg)
13 
14     @talk.deleter
15     def talk(self):
16         print("delet talk...")
17 
18 p = person("alex")
19 p.talk #调用不需要加(),相当于你访问的变量其实是一个方法 读取值
20 p.talk = "hello" #这个赋值变量在调用方法 修改值
21 del p.talk #这个是删除 删除值
22 #作用可以参考航班实例

 

5.其他方法

 1 print("其他方法".center(20,#))
 2 class person(object):
 3     ‘‘‘hahahahahah‘‘‘
 4     def __init__(self,name):
 5         self.name = name
 6     def tell(self):
 7         print("what do you say... %s" % self.name)
 8 p = person("jack")
 9 p.tell()
10 print(p.__doc__) #打印类的注释打印  hahahahah
11 print(p.__module__) #当前哪个模块  __main__表示当前的某块就在当前
12 print(p.__class__) #当前哪个类
13 
14 #***当属性方法航班状态查询加个判断if __name__ == ‘__main__‘:
15 #这样的话在被调用的时候执行了以上的代码,而不被调用一下的调用
16 
17 # print("字符串导入模块".center(20,‘#‘))
18 # from day import 属性方法航班状态查询
19 # mod = __import__(‘day8work.属性方法航班状态查询‘)
20 # print(mod.属性方法航班状态查询.Filght(‘ca980‘))

 

6.创建类的方法

 1 print("meta".center(20,#))
 2 #普通创建类的方法
 3 class Foo(object):
 4     def __init__(self, name):
 5         self.name = name
 6 f = Foo("alex")
 7 print(type(f)) #f 由foo  foo由 type  生成
 8 print(type(Foo))
 9 #特殊方法创建类
10 def talk(self,msg):
11     print("%s is talking:%s" % (self.name,msg)) #里面小括号续加上,不然调用不了
12 def __init__(self,name):
13     self.name = name
14 dog = type(dog,(object,),{"talk":talk,"__init__":__init__})
15 print(dog)
16 d = dog("alex")
17 d.talk("eat")

 

7.异常处理基本机构种类

 1 print("异常处理".center(20,#))
 2 # while True:
 3 #     try:
 4 #         a1 = input(‘>>>‘)
 5 #         a2 = input(‘>>>‘)
 6 #         a1 = int(a1)
 7 #         a2 = int(a2)
 8 #         a3 = a1 + a2
 9 #         print(a3)
10 #     except Exception as e:
11 #         # print(e) #e 里面包括的错误信息
12 #         print("你输入的错误")
13 #基本结构
14 # try:
15 #     代码块
16 #     代码块
17 # except Exception as e:  e 其实就是exception的对象,可以使用其他名称代替
18 #     将错误信息写入日志文件
19 
20 #复杂结构
21 # try:
22 #     ...
23 # except:
24 #     ...
25 # else: 没有错误的时候执行
26 #     ...
27 # finally:  正确与否,代码肯定要执行的
28 #     ...
29 
30 #异常对象
31 try:
32     int(fdsfdsf)
33 except Exception as e:
34     print(e)   #invalid literal for int() with base 10: ‘fdsfdsf‘
35 
36 try:
37     li = [11,22]
38     li[3]
39 except Exception as e: #python内部将错误信息封装到e的对象中,就是exceptino
40     print(e) #list index out of range
41 
42 #异常种类
43 #Exception #能将所有的异常都捕获
44 # ...
45 # 其他     只能处理某一种情况
46 # try:
47 #     代码块
48 #     代码块
49 # except ValueErroras e:
50 #     将错误信息写入日志文件
51 # except KeyError as e:
52 #     将错误信息写入日志文件
53 # except Exception as e:
54 #     将错误信息写入日志文件
55 # ValueError  可以替换Exception
56 # KeyError
57 # IOError
58 # IndexError

 

8.主动触发异常,程序分层

 1 #主动触发异常  程序分层
 2 try:
 3     raise Exception(error) #主从触发将错误信息封装到e里面
 4 except Exception as e:
 5     print(e)
 6 
 7 # try:
 8 #     result = fool()    拿到返回值来判断,就是没有异常,但是邮件没有发送成功
 9 #     if result:
10 #         pass
11 #     else:
12 #         raise Exception(‘邮件发送失败‘)
13 #     foo2()
14 # except Exception as e:
15 #     记录日志

 

9.断言

1 print("断言".center(20,#))
2 #ios 去打开 安卓的app是不是直接就断开了
3 #所以在开始之前先判断,例如系统
4 # assert(关键字) 条件
5 print(1)
6 assert 1==1   # assert 1==2  只显示1并且抛出错误
7 print(2)

 

10.自定义异常

 1 print("自定义异常".center(20,#))
 2 #开发一个类,来继承exception 来实现满足你自己定义的异常
 3 class lilierror(Exception):
 4     def __init__(self,msg):
 5         self.msg = msg
 6         super(lilierror,self).__init__(msg)#执行父类的构造方法
 7 try:#如果想要打印出来msg必须加上,不然父类不知道
 8     name = alex
 9     if name != lili:
10         raise lilierror(哈哈哈 lili我错了)
11 except IndexError as e:
12     print(e)
13 except lilierror as e:
14     print(e,e.msg)  #这个就是调用类方法来显示了
15 except Exception as e:
16     print(e,1111)
17 #重点  1 2 3 4 5  断言和自定义异常很少用  基本代码块+主动触发异常

 

11.反射

 1 #反射写法
 2 # inp = input("请输入url")     #account/login
 3 # m,n = inp.split(‘/‘)  #m account  n login
 4 # from  dir import app
 5 # action = input(‘>>‘)  #可以用户输入
 6 # # if(hasattr(app,action)):
 7 #     func =getattr(account,action)
 8 # v = getattr(app,action)
 9 # result = v()
10 # print(result)
11 
12 #getattr() 专以字符串的形式去某个对象中获取指定的属性
13 #hasattr() 以字符串的形式去某个对象中是否含有指定的属性
14 #setattr(容器,名称,值) 以字符串的形式去某个对象中设置指定的属性
15 #delattr() 以字符串的形式去某个对象中删除指定的属性
16 
17 # from  dir import app
18 # action = input(‘>>‘)  #可以用户输入
19 # if(hasattr(app,action)):
20 #     func =getattr(account,action)
21 #     result = func()
22 #     else
23 #     result = ‘404‘
24 #     print(result)
25 
26 #反射最终版
27 #通过字符串导入模块,可以实现某块/函数  这样的话通过/分割,就可以实现直接调用
28 #module = __import__(‘dir.app‘,formlist=Ture)  这样的话相当于导入模块不加TRUE的话,前面是什么就是什么了
29 # while True:
30 #     inp = input("请输入url")
31 #     m,n = inp.split(‘/‘)
32 #     try:
33 #         module = __import__(‘dir.%s‘ % m,fromlist=True)
34 #         if hasattr(module,n):
35 #             func =getattr(module,n)
36 #             result = func()
37 #         else:
38 #             result = 404
39 #     except Exception as e:
40 #         result = ‘500‘
41 #     print(result)

 

12.socket编程

 1 #socket   osi 七层   tcp 三次握手
 2 #服务器端
 3 #socket.socket(AF_INET,SOCK_STREAM) 先创建sock实例
 4 #server.bind(‘0.0.0.0‘,8000)  监听Ip端口
 5 #server.listen(5)  可以多个并列
 6 #server.accept()  接收请求
 7 #conn(建立链接),client_addr(地址) = server.accept()
 8 #conn.send()  发送消息
 9 #conn.recv()  接收消息
10 #server.close()
11 #server.send()
12 
13 #客户端
14 # socket.socket(AF_INET,SOCK_STREAM)
15 # client.connect()
16 # client.send()

 

12.socket编程  c s架构

client 端的代码量

技术分享
 1 #!/usr/bin/env python
 2 #_*_coding:utf-8_*_
 3 
 4 # import socket
 5 # client = socket.socket()
 6 # client.connect(("localhost",9998))
 7 # while True:
 8 #     msg = input(">>:").strip()
 9 #     if len(msg) == 0: continue
10 #     client.send(msg.encode("utf-8"))
11 #     data = http://www.mamicode.com/client.recv(1024)
12 #     print("来自服务器:", data)
13 # client.close()
14 
15 
16 #基本结构
17 # import socket
18 # client = socket.socket()
19 # client.connect((‘localhost‘,8000))
20 # client.send(b‘hello‘)
21 # date = client.recv(1024)
22 # print(date)
23 
24 #
25 # #循环收发
26 # import socket
27 # client = socket.socket()
28 # client.connect((‘localhost‘,8000))
29 # while True:
30 #     client.send(b‘hello‘)
31 #     date = client.recv(1024)
32 #     print(date)
33 
34 
35 #单循环客户发送信息
36 # import socket
37 # client = socket.socket()
38 # client.connect((‘localhost‘,8000))
39 # while True:
40 #     msg = input(‘>>>:‘).strip()
41 #     if len(msg) == 0: continue
42 #     client.send(msg.encode())
43 #     date = client.recv(1024)
44 #     print(‘laizisever‘,date)
45 
46 
47 #排列链接
48 # import socket
49 # client = socket.socket()
50 # client.connect((‘localhost‘,8000))
51 # while True:
52 #     msg = input(‘>>>:‘).strip()
53 #     if len(msg) == 0: continue
54 #     client.send(msg.encode())
55 #     date = client.recv(1024)
56 #     print(‘laizisever‘,date)
57 #
58 
59 #调用Linux系统命令实现ssh  top -bn 1
60 # import socket
61 # client = socket.socket()
62 # client.connect((‘10.10.10.140‘,8002))
63 # while True:
64 #     msg = input(‘>>>:‘).strip()
65 #     if len(msg) == 0: continue
66 #     print(‘to server‘, msg)
67 #     client.send(msg.encode())
68 #     date = client.recv(1024)
69 #     print(date.decode())
70 
71 
72 #调用Linux系统命令实现ssh  top -bn 1   将接收大文件数据
73 import socket
74 client = socket.socket()
75 client.connect((10.10.10.140,8002))
76 while True:
77     msg = input(>>>:).strip()
78     if len(msg) == 0: continue
79     print(to server, msg)
80     client.send(msg.encode())
81     date = client.recv(1024)
82     print("res:",date.decode())
83     total_size = int(date.decode())
84     recevied_size = 0
85     res = b‘‘
86     while recevied_size < total_size:
87         d = client.recv(1024)
88         res += d
89 
90         recevied_size += len(d)
91     print("rece done----")
92     print(res.decode())
View Code

server 端的代码量

技术分享
  1 #!/usr/bin/env python
  2 #_*_coding:utf-8_*_
  3 
  4 
  5 # import socket
  6 # server = socket.socket() #获得socket实例
  7 #
  8 # server.bind(("localhost",9998)) #绑定ip port
  9 # server.listen()  #开始监听
 10 # print("等待客户端的连接...")
 11 # conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
 12 # print("新连接:",addr )
 13 # while True:
 14 #     data = http://www.mamicode.com/conn.recv(1024)
 15 #     print("收到消息:",data)
 16 #     conn.send(b"server")
 17 # server.close()
 18 
 19 
 20 #基本结构
 21 # import socket
 22 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 23 # server.bind((‘0.0.0.0‘,8000))
 24 # server.listen(5)
 25 # # print("hahahahaha")
 26 # conn,client_addr = server.accept()
 27 # print(conn,client_addr)
 28 # date = conn.recv(1024)
 29 # conn.send(b‘woshisever‘)
 30 # print(date)
 31 
 32 # #循环收发
 33 # import socket
 34 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 35 # server.bind((‘0.0.0.0‘,8000))
 36 # server.listen(5)
 37 # conn,client_addr = server.accept()
 38 #
 39 # while True:
 40 #     date = conn.recv(1024)
 41 #     print(‘shoudao client‘,date)
 42 #     conn.send(b‘woshisever‘)
 43 
 44 
 45 
 46 #单循环收发客户端信息
 47 # import socket
 48 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 49 # server.bind((‘0.0.0.0‘,8000))
 50 # server.listen(5)
 51 # conn,client_addr = server.accept()
 52 #
 53 # while True:
 54 #     date = conn.recv(1024)
 55 #     print(‘shoudao client‘,date)
 56 #     conn.send(b‘woshisever‘)
 57 
 58 
 59 #排列链接,当一个断块,另一个可以链接
 60 # import socket
 61 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 62 # server.bind((‘0.0.0.0‘,8000))
 63 # server.listen(5)
 64 #
 65 # while True:
 66 #     conn,client_addr = server.accept()
 67 #
 68 #     while True:
 69 #         try:
 70 #             date = conn.recv(1024)
 71 #             print(‘shoudao client‘,date)
 72 #             conn.send(b‘woshisever‘)
 73 #         except ConnectionResetError as e:
 74 #             print(e)
 75 #             break
 76 
 77 
 78 #调用Linux系统命令实现ssh
 79 # import socket
 80 # import subprocess
 81 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 82 # server.bind(("0.0.0.0",8002))
 83 # server.listen(5)
 84 # print("--------listen-----------")
 85 #
 86 # while True:
 87 #     conn,client_addr = server.accept()
 88 #     while True:
 89 #         date = conn.recv(1024)
 90 #         print("recv from cli:",date)
 91 #         res = subprocess.Popen(date,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
 92 #         conn.send(res.stdout.read())
 93 
 94 
 95 #调用Linux系统命令实现ssh  实现大数据返回消息
 96 # import socket
 97 # import subprocess
 98 # server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 99 # server.bind(("0.0.0.0",8002))
100 # server.listen(5)
101 # print("--------listen-----------")
102 #
103 # while True:
104 #     conn,client_addr = server.accept()
105 #     while True:
106 #         date = conn.recv(1024)
107 #         print("recv from cli:",date)
108 #         res_obj = subprocess.Popen(date,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
109 #         res = res_obj.stdout.read()
110 #         conn.send(str(len(res)).encode())
111 #         conn.send(res)
View Code

 

python学习道路(day8note)(抽象类,类的方法,异常处理,socket编程)