s12-20160227-day07

*:first-child {
margin-top: 0 !important;
}

body>*:last-child {
margin-bottom: 0 !important;
}

/* BLOCKS
=============================================================================*/

p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}

/* HEADERS
=============================================================================*/

h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}

h1 {
font-size: 28px;
color: #000;
}

h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}

h3 {
font-size: 18px;
}

h4 {
font-size: 16px;
}

h5 {
font-size: 14px;
}

h6 {
color: #777;
font-size: 14px;
}

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}

/* LINKS
=============================================================================*/

a {
color: #4183C4;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

/* LISTS
=============================================================================*/

ul, ol {
padding-left: 30px;
}

ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}

ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}

dl {
padding: 0;
}

dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}

dl dt:first-child {
padding: 0;
}

dl dt>:first-child {
margin-top: 0px;
}

dl dt>:last-child {
margin-bottom: 0px;
}

dl dd {
margin: 0 0 15px;
padding: 0 15px;
}

dl dd>:first-child {
margin-top: 0px;
}

dl dd>:last-child {
margin-bottom: 0px;
}

/* CODE
=============================================================================*/

pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}

code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}

pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}

pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}

pre code, pre tt {
background-color: transparent;
border: none;
}

kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}

/* QUOTES
=============================================================================*/

blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}

blockquote>:first-child {
margin-top: 0px;
}

blockquote>:last-child {
margin-bottom: 0px;
}

/* HORIZONTAL RULES
=============================================================================*/

hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}

/* TABLES
=============================================================================*/

table th {
font-weight: bold;
}

table th, table td {
border: 1px solid #ccc;
padding: 6px 13px;
}

table tr {
border-top: 1px solid #ccc;
background-color: #fff;
}

table tr:nth-child(2n) {
background-color: #f8f8f8;
}

/* IMAGES
=============================================================================*/

img {
max-width: 100%
}
-->

pytho自动化开发 day07

Date:2016.02.27

  1. @南非波波

课程大纲:

day06

http://www.cnblogs.com/alex3714/articles/5188179.html

day07

http://www.cnblogs.com/alex3714/articles/5213184.html

一、类的多态、继承

类的多态:统一接口调用

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. class Animal:
  4. def __init__(self, name): # Constructor of the class
  5. self.name = name
  6. def talk(self): # Abstract method, defined by convention only
  7. raise NotImplementedError("Subclass must implement abstract method")
  8. hobbie = 'ddd'
  9. class Cat(Animal):
  10. def talk(self):
  11. return 'Meow!'
  12. class Dog(Animal):
  13. def talk(self):
  14. return 'Woof! Woof!'
  15. animals = [Cat('Missy'),
  16. Dog('Lassie')]
  17. for animal in animals:
  18. print(animal.name + ': ' + animal.talk())

类的方法:示例

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. class Animal(object):
  8. '''
  9. 定义一个动物类
  10. '''
  11. def __init__(self,name):
  12. self.name = name
  13. self.__num = None #定义成私有变量,只能在类中访问
  14. # def talk(self):
  15. # print("%s is talking!" % self.name)
  16. hobbie = "shen" #类变量,静态字段
  17. @classmethod #类方法,不能访问实例变量
  18. def talk(self):
  19. print("%s is talking!" % self.hobbie)
  20. # def work(self):
  21. # print("%s is working!" % self.name)
  22. @staticmethod #静态方法,不能访问类变量和实例变量
  23. def work():
  24. print("It is working!")
  25. # def walk(self):
  26. # print("%s is walking!" % self.name)
  27. @property #把方法编程静态属性
  28. def walk(self,num):
  29. return self.__num
  30. @walk.setter #传值
  31. def walk(self,num):
  32. self.__num = num
  33. print(self.__num)
  34. @walk.deleter #删值
  35. def walk(self):
  36. print("del num")
  37. c = Animal("swht")
  38. # c.talk()
  39. # c.work()
  40. c.walk = 3
  41. del c.walk
  42. print("OUT:",c._Animal__num) #特例情况下可以通过这种方式访问私有变量

经典类与新式类

经典类和新式类区别:

经典类:使用深度优先进行继承 新式类:使用广度优先进行继承

另外:经典类和新式类在python-3.X平台上会默认使用广度优先进行继承,而在python-2.X中则体现上述区别

示例代码:

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. class A:
  8. print("A")
  9. def f2(self):
  10. print("f2 from A")
  11. class B(A):
  12. print("B")
  13. def f1(self):
  14. print("f1 from B")
  15. def f2(self):
  16. print("f2 from B")
  17. class C(A):
  18. print("C")
  19. def f2(self):
  20. print("f2 from C")
  21. class D(B,C):
  22. pass
  23. d = D()
  24. d.f1()
  25. d.f2()
  26. '''
  27. 广度优先算法继承。先将B类中的f2()注释掉,D自动继承C.f2(),如果再将C类中的f2(),D自动继承A.f2()
  28. '''

类的特殊成员

  1. __doc__:查看类的注释
  2. __init__:构造方法,通过类创建对象时,自动触发执行。
  3. __module__:表示当前操作的对象在那个模块
  4. __class__:表示当前操作的对象的类是什么
  5. __del__:析构方法,解释器进行垃圾回收时自动触发
  6. __call__:对象加()执行call方法
  7. __new__:实例化时new方法执行了__init__
  8. __metaclass__:通过改写metaclass方法达到构建自己需要的类的目的
  9. __dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
  10. __str__:如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
  11. __iter__:用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__

示例:

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. class People(object):
  8. '''
  9. 定义一个人类
  10. '''
  11. def __init__(self,name,age):
  12. '''
  13. 定义属性
  14. :param name: 人类的名字
  15. :param age: 人类的年龄属性
  16. :return:
  17. '''
  18. self.name = name
  19. self.age = age
  20. def china_man(self):
  21. pass
  22. chinese = People("swht",27)
  23. #__doc__:查看类的注释
  24. print(chinese.__doc__) # 定义一个人类
  25. #__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
  26. print(chinese.__dict__) #{'age': 27, 'name': 'swht'}
  27. #__module__:表示当前操作的对象在那个模块
  28. print(chinese.__module__) #__main__
  29. #__class__:表示当前操作的对象的类是什么
  30. print(chinese.__class__) #<class '__main__.People'>

构造类的方法

http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

一句话构建一个类

  1. Foo = type('Foo',(object,), {'func': func})
  2. #type第一个参数:类名
  3. #type第二个参数:当前类的基类
  4. #type第三个参数:类的成员

反射方法

hasattr:判断实例中是否存在指定输入的方法

  1. hasattr(server,sys.argv[1]) 返回值是布尔型 True or False

getattr:获取实例中的方法

  1. func = getattr(server,sys.argv[1]) 获取对象方法的内存地址

setattr:将自定义的某个方法设定到特定实例中去使用

  1. setattr(server,'run',test_run) 将特定方法test_run绑定给实例server,并重命名为run方法
  2. server.run() 实例server可以指定调用方法run

delattr:删除实例的成员变量或者类的方法,不能删除实例的方法

  1. #delattr可以删除类的方法、实例的成员变量
  2. # delattr(server,'start') #尝试删除实例的方法是错误的
  3. # delattr(server,"host") #删除实例的变量
  4. # delattr(Webserver,'start')
  5. # server.start() #AttributeError: 'Webserver' object has no attribute 'start'

完整示例代码:

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import sys
  8. class Webserver(object):
  9. '''
  10. 定义一个web server启动、关闭类
  11. '''
  12. def __init__(self,host,port):
  13. '''
  14. 初始化类
  15. :param host: 主机地址
  16. :param port: 主机端口号
  17. :return:
  18. '''
  19. self.host = host
  20. self.port = port
  21. def start(self):
  22. '''
  23. 服务启动方法
  24. :return:
  25. '''
  26. print("service is starting...")
  27. def stop(self):
  28. '''
  29. 服务停止方法
  30. :return:
  31. '''
  32. print("service is stopping ...")
  33. def restart(self):
  34. '''
  35. 服务重启方法
  36. :return:
  37. '''
  38. self.stop()
  39. self.start()
  40. #定义一个特殊运行的函数,绑定到实例server上去
  41. def test_run():
  42. print("测试运行...")
  43. server = Webserver("localhost",80)
  44. if hasattr(server,sys.argv[1]):
  45. func = getattr(server,sys.argv[1])
  46. func()
  47. #setattr主要作用是将一个单独定义的函数添加到实例中,对于类或者其他实例而言,该函数对其不生效
  48. setattr(server,'run',test_run)
  49. server.run()
  50. #delattr可以删除类的方法、实例的成员变量
  51. # delattr(server,'start') #尝试删除实例的方法是错误的
  52. # delattr(server,"host") #删除实例的变量
  53. # delattr(Webserver,'start')
  54. # server.start() #AttributeError: 'Webserver' object has no attribute 'start'

二、socket网络编程

简单实现C/S交互实例:

示例代码:

  1. 实现简单的clientserver端数据交互(一句话)

socket_server

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. ip_port = ("127.0.0.1",5000)
  9. sk = socket.socket()
  10. sk.bind(ip_port)
  11. sk.listen(5)
  12. while True:
  13. print("南非波波server is Listening....")
  14. conn,addr = sk.accept()
  15. client_data = conn.recv(1024)
  16. print(str(client_data,"utf8"))
  17. conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
  18. conn.close()

socket_client

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. ip_port = ("127.0.0.1",5000)
  9. sk = socket.socket()
  10. sk.connect(ip_port)
  11. sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))
  12. server_reply = sk.recv(1024)
  13. print(str(server_reply,"utf8"))
  14. sk.close()

改善代码1:

  1. 实现多个clientserver进行串行交互

socket-server1

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. ip_port = ("127.0.0.1",5000)
  9. sk = socket.socket()
  10. sk.bind(ip_port)
  11. sk.listen(5)
  12. while True:
  13. print("南非波波server is Listening....")
  14. conn,addr = sk.accept()
  15. client_data = conn.recv(1024)
  16. print(str(client_data,"utf8"))
  17. # conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
  18. while True:
  19. try:
  20. client_data = conn.recv(1024)
  21. if not client_data:
  22. break
  23. print("recv:",str(client_data,"utf8"))
  24. conn.send(client_data)
  25. except Exception:
  26. print("客户端断开!")
  27. break
  28. conn.close()

socket-client1

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. ip_port = ("127.0.0.1",5000)
  9. sk = socket.socket()
  10. sk.connect(ip_port)
  11. # sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))
  12. server_reply = sk.recv(1024)
  13. print(str(server_reply,"utf8"))
  14. while True:
  15. client_data = input(">>:").strip()
  16. if not client_data:
  17. continue
  18. if client_data == 'q':
  19. break
  20. sk.send(bytes(client_data,"utf8"))
  21. print(client_data)
  22. sk.close()

最终代码:

  1. 实现简单的ssh命令交互,获取Linux系统的相关信息

socket-server2

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. import subprocess
  9. ip_port = ("127.0.0.1",5000) #定义服务监听的ip地址和端口
  10. ssh = socket.socket()
  11. ssh.bind(ip_port) #进行地址和端口绑定
  12. ssh.listen(5) #设定做多5个并发连接
  13. while True:
  14. print("南非波波Server is waiting...")
  15. conn,addr = ssh.accept()
  16. while True:
  17. client_data = conn.recv(1024) #介绍client发过来的数据,最大接收字节1024
  18. if not client_data: #如果client_data为空,则跳出循环
  19. break
  20. cmd = str(client_data,"utf8") #获取client_data数据并进行类型和编码转换
  21. print("server recv:",cmd)
  22. cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) #以原生shell命令的形式指定client的强求指定,并将结果输出到cmd_result
  23. cmd_result = cmd_call.stdout.read()
  24. if len(cmd_result) == 0: #如果命令没有结果返回,则需要给client返回一个提示,否则控制台会阻塞
  25. cmd_result = b"cmd execution has no output.."
  26. #client不能一次性接收过多的数据包,需要server端先告知client端需要传输的数据多少。然后由client端分开接收
  27. ack_msg = bytes("CMD_RESULT_SIZE|%s" % len(cmd_result),"utf8") #发送数据传输认证标志
  28. conn.send(ack_msg)
  29. client_ack = conn.recv(50)
  30. if client_ack.decode() == 'CLIENT_READY_TO_RECV':
  31. conn.send(cmd_result) #数据传输
  32. conn.close()

socket-client2

  1. #!/usr/local/env python3
  2. '''
  3. Author:@南非波波
  4. Blog:http://www.cnblogs.com/songqingbo/
  5. E-mail:qingbo.song@gmail.com
  6. '''
  7. import socket
  8. ip_port = ("127.0.0.1",5000)
  9. ssh_client = socket.socket()
  10. ssh_client.connect(ip_port)
  11. while True:
  12. user_input = input("ssh-client:").strip()
  13. if len(user_input) == 0:
  14. continue
  15. if user_input == 'q':
  16. break
  17. ssh_client.send(bytes(user_input,'utf8'))
  18. #ack_msg = b"CMD_RESULT_SIZE|%s" % len(cmd_result)
  19. server_ack_msg = ssh_client.recv(100)
  20. cmd_res_msg = str(server_ack_msg.decode()).split("|")
  21. if cmd_res_msg[0] == "CMD_RESULT_SIZE":
  22. cmd_res_size = int(cmd_res_msg[1])
  23. ssh_client.send(b"CLIENT_READY_TO_RECV")
  24. res = ''
  25. received_size = 0
  26. while received_size < cmd_res_size:
  27. server_data = ssh_client.recv(500)
  28. received_size += len(server_data)
  29. res += str(server_data.decode())
  30. else:
  31. print(res)
  32. print("-----------recv don----------")
  33. ssh_client.close()

python开发学习-day07(面向对象之多态、类的方法、反射、新式类and旧式类、socket编程)的更多相关文章

  1. python开发学习-day06(模块拾忆、面向对象)

    s12-20160130-day06 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...

  2. python基础学习Day17 面向对象的三大特性之继承、类与对象名称空间小试

    一.课前回顾 类:具有相同属性和方法的一类事物 实例化:类名() 过程: 开辟了一块内存空间 执行init方法 封装属性 自动的把self返回给实例化对象的地方 对象:实例 一个实实在在存在的实体 组 ...

  3. python基础学习 Day19 面向对象的三大特性之多态、封装 property的用法(1)

    一.课前内容回顾 继承作用:提高代码的重用性(要继承父类的子类都实现相同的方法:抽象类.接口) 继承解释:当你开始编写两个类的时候,出现了重复的代码,通过继承来简化代码,把重复的代码放在父类中. 单继 ...

  4. python基础学习 Day19 面向对象的三大特性之多态、封装

    一.课前内容回顾 继承作用:提高代码的重用性(要继承父类的子类都实现相同的方法:抽象类.接口) 继承解释:当你开始编写两个类的时候,出现了重复的代码,通过继承来简化代码,把重复的代码放在父类中. 单继 ...

  5. python开发学习-day01 (python安装与版本、字符串、字典、运算符、文件)

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  6. python 面向对象之多态与绑定方法

    多态与多态性 一,多态 1,多态指的是一类事物有多种形态(python里面原生多态) 1.1动物有多种形态:人,狗,猪 import abc class Animal(metaclass=abc.AB ...

  7. python开发学习-day10(select/poll/epoll回顾、redis、rabbitmq-pika)

    s12-20160319-day10 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...

  8. python开发学习-day02(元组、字符串、列表、字典深入)

    s12-20160109-day02 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...

  9. python开发学习-day03(set集合、collection系列 、深浅拷贝、函数)

    s12-20160116-day03 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...

随机推荐

  1. C/C++ string.h头文件小结

    http://note.youdao.com/noteshare?id=cff515f7b683f579d22f17b54b960e2a

  2. grep index.php *

    zb@zb-computer:/usr/local/nginx/conf/vhost$ grep index.php * caomall17.conf: index index.html index. ...

  3. Kubernetes 1.5通过Ceph实现有状态容器

    在上一篇博文,我们通过kubernetes的devlopment和service完成了sonarqube的部署.看起来已经可用,但是仍然有一个很大的问题.我们知道,像mysql这种数据库是需要保存数据 ...

  4. nova-virt与libvirt

    源码版本:H版 nova通过nova/virt/driver.py中的ComputeDriver对底层虚拟化技术进行抽象,不同的虚拟化技术在nova/virt下有不同的目录,里面均有driver.py ...

  5. C++ string的那些坑

    1. size_type find_first_of( const basic_string &str, size_type index = 0 ); 查找在字符串中第一个与str中的某个字符 ...

  6. DialogFragment 将数据传回Activity的onActivityResult方法

    在MyActivity中 弹出一个DialogFragment (某一个控件的点击事件) search= findViewById(R.id.search); search.setOnClickLis ...

  7. GridControl详解(七)事件

    private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventA ...

  8. 最常用的8款 PHP 调试工具,你用过吗?

    Web 开发并不是一项轻松的任务,有超级多服务端脚本语言提供给开发者,但是当前 PHP 因为具有额外的一些强大的功能而越来越流行.PHP 是最强大的服务端脚本语言之一,同时也是 Web 开发者和设计者 ...

  9. VC改变CListCtrl 表格中文字颜色,和背景颜色。

    (1)首先需要自定义一个类,派生自CListCtrl.如下图: (2)然后在派生类的头文件中声明一个成员函数,如下图: (3)在源文件中实现该成员方法,如图: (4)在源文件中做消息映射,如图: 这时 ...

  10. js_网页导出pdf文件

    打印当前页面,一开始我认为是需要输出pdf的,后来了解的需求是能够打印就可以了.需求既然都研究了,记录下. 更好的打印方式,window.print();会弹出打印对话框,打印的是window.doc ...