Python Development Learning-day07 (object-oriented polymorphism, class method, reflection, new class and Legacy class, socket programming)

Source: Internet
Author: User

S12-20160227-day07

Pytho Automation Development day07date:2016.02.27
    @南非波波

Course Outline:

Day06

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

Day07

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

I. Polymorphism and inheritance of classes

Polymorphism of the class: Unified interface Invocation

#!/usr/bin/env python# -*- coding:utf-8 -*-class Animal:    def __init__(self, name):    # Constructor of the class        self.name = name    def talk(self):              # Abstract method, defined by convention only        raise NotImplementedError("Subclass must implement abstract method")    hobbie = ‘ddd‘class Cat(Animal):    def talk(self):        return ‘Meow!‘class Dog(Animal):    def talk(self):        return ‘Woof! Woof!‘animals = [Cat(‘Missy‘),           Dog(‘Lassie‘)]for animal in animals:    print(animal.name + ‘: ‘ + animal.talk())

Methods of the class: example

#!/usr/local/env Python3 "author:@ South Africa bobo Blog:http://www.cnblogs.com/songqingbo/e-mail:[email protected]" Class Animal (object): ' Defines an animal class ' Def __init__ (self,name): self.name = name Self.__num = Non E #定义成私有变量, can only be accessed in the class # Def talk (self): # print ("%s is talking!"% self.name) Hobbie = "Shen" #类变量, static fields @clas Smethod #类方法, cannot access instance variable def talk (self): print ('%s is talking! '% self.hobbie) # def work (self): # print    ("%s is working!"% self.name) @staticmethod #静态方法, cannot access class variables and instance variables def work (): Print ("It is working!") # def walk (self): # print ("%s is walking!"% self.name) @property #把方法编程静态属性 def Walk (self,num): retur  n self.__num @walk. Setter #传值 def Walk (self,num): Self.__num = num print (self.__num) @walk. deleter #删值 def Walk (self): print ("del num") c = Animal ("swht") # C.talk () # c.work () C.walk = 3del C.walkprint ("Out:", c._a Nimal__num) #特例情况下可以通过这种方式访问私有变量

Classic class and Modern class

Classic class and new class differences:

Classic class: Inherit with depth precedence new class: Inherit with breadth precedence

In addition: Classic class and New class in Python-3. The X platform will default to the use of breadth-first inheritance, while in Python-2. This difference is reflected in X

Example code:

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘class A:    print("A")    def f2(self):        print("f2 from A")class B(A):    print("B")    def f1(self):        print("f1 from B")    def f2(self):        print("f2 from B")class C(A):    print("C")    def f2(self):        print("f2 from C")class D(B,C):    passd = D()d.f1()d.f2()‘‘‘广度优先算法继承。先将B类中的f2()注释掉,D自动继承C.f2(),如果再将C类中的f2(),D自动继承A.f2()‘‘‘

Special members of the class

Example:

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘class People(object):    ‘‘‘    定义一个人类    ‘‘‘    def __init__(self,name,age):        ‘‘‘        定义属性        :param name: 人类的名字        :param age: 人类的年龄属性        :return:        ‘‘‘        self.name = name        self.age = age    def china_man(self):        passchinese = People("swht",27)#__doc__:查看类的注释print(chinese.__doc__) #  定义一个人类#__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)print(chinese.__dict__) #{‘age‘: 27, ‘name‘: ‘swht‘}#__module__:表示当前操作的对象在那个模块print(chinese.__module__) #__main__#__class__:表示当前操作的对象的类是什么print(chinese.__class__) #<class ‘__main__.People‘>

Methods for constructing classes

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

A sentence constructs a class

Foo = type(‘Foo‘,(object,), {‘func‘: func})     #type第一个参数:类名    #type第二个参数:当前类的基类    #type第三个参数:类的成员

Reflection method

Hasattr: Determines whether the specified input method exists in the instance

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

GetAttr: Getting methods in an instance

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

SetAttr: Setting a custom method to a specific instance to use

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

Delattr: Delete the instance's member variable or the method of the class, cannot delete the instance's method

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

Complete Sample code:

#!/usr/local/env Python3 "author:@ South Africa bobo Blog:http://www.cnblogs.com/songqingbo/e-mail:[email protected]"        Import Sysclass Webserver (object): ' Define a Web server to start, close class ' Def __init__ (self,host,port): ' Initialize class:p Aram Host: Host address:p Aram Port: Host port number: return: "' Self.host = host SELF.P    ORT = Port def start (self): "Service startup method: return:" ' Print ("Services is starting ...") def stop (self): "Service Stop Method: return:" Print ("service is stopping ...") def rest Art (self): "Service Restart Method: return: ' ' Self.stop () Self.start () #定义一个特殊运行的函数, bound to instance Ser Ver go up def test_run (): Print ("Test run ...") Server = Webserver ("localhost", +) if Hasattr (Server,sys.argv[1]): func = Getatt R (Server,sys.argv[1]) func () #setattr主要作用是将一个单独定义的函数添加到实例中, the function does not take effect for a class or other instance setattr (server, ' run ', Test_run) Server.run () #delattr可以删除类的方法, member variable of instance # delattr (sErver, ' start ') #尝试删除实例的方法是错误的 # delattr (server, "host") #删除实例的变量 # delattr (Webserver, ' start ') # Server.start () # Attributeerror: ' Webserver ' object has no attribute ' start '
Second, Socket network programming

Simple implementation of C/s Interactive example:

Example code:

实现简单的client与server端数据交互(一句话)

Socket_server

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘import socketip_port = ("127.0.0.1",5000)sk = socket.socket()sk.bind(ip_port)sk.listen(5)while True:    print("南非波波server is Listening....")    conn,addr = sk.accept()    client_data = conn.recv(1024)    print(str(client_data,"utf8"))    conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))    conn.close()

Socket_client

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘import socketip_port = ("127.0.0.1",5000)sk = socket.socket()sk.connect(ip_port)sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))server_reply = sk.recv(1024)print(str(server_reply,"utf8"))sk.close()

Improve code 1:

实现多个client与server进行串行交互

Socket-server1

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘import socketip_port = ("127.0.0.1",5000)sk = socket.socket()sk.bind(ip_port)sk.listen(5)while True:    print("南非波波server is Listening....")    conn,addr = sk.accept()    client_data = conn.recv(1024)    print(str(client_data,"utf8"))    # conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))    while True:        try:            client_data = conn.recv(1024)            if not client_data:                break            print("recv:",str(client_data,"utf8"))            conn.send(client_data)        except Exception:            print("客户端断开!")            break    conn.close()

Socket-client1

#!/usr/local/env python3‘‘‘Author:@南非波波Blog:http://www.cnblogs.com/songqingbo/E-mail:[email protected]‘‘‘import socketip_port = ("127.0.0.1",5000)sk = socket.socket()sk.connect(ip_port)# sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))server_reply = sk.recv(1024)print(str(server_reply,"utf8"))while True:    client_data = input(">>:").strip()    if not client_data:        continue    if client_data == ‘q‘:        break    sk.send(bytes(client_data,"utf8"))    print(client_data)sk.close()

Final code:

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

Socket-server2

#!/usr/local/env Python3 "author:@ South Africa bobo Blog:http://www.cnblogs.com/songqingbo/e-mail:[email protected]" Import Socketimport Subprocessip_port = ("127.0.0.1", "") #定义服务监听的ip地址和端口ssh = Socket.socket () ssh.bind (ip_port) # Address and port Binding Ssh.listen (5) #设定做多5个并发连接while True:print ("South Africa Bobo server is waiting ...") conn,addr = Ssh.accept () while Tr            Ue:client_data = Conn.recv (1024x768) #介绍client发过来的数据, maximum receive byte if not client_data: #如果client_data为空, jump out of loop Break cmd = str (client_data, "UTF8") #获取client_data数据并进行类型和编码转换 print ("Server recv:", cmd) cmd_ Call = subprocess. Popen (cmd,shell=true,stdout=subprocess. PIPE) #以原生shell命令的形式指定client的强求指定 and output the result to cmd_result Cmd_result = Cmd_call.stdout.read () If Len (cmd_result) =        = 0: #如果命令没有结果返回, you need to return a prompt to the client, otherwise the console will block Cmd_result = B "cmd execution has no output ..." #client不能一次性接收过多的数据包, the server is required to tell the client how much data needs to be transferred. It is then received separately by the client side ack_msg = bytes ("cmd_result_size|%s"% Len (cmd_resuLT), "UTF8") #发送数据传输认证标志 conn.send (ack_msg) Client_ack = Conn.recv () if client_ack.decode () = = ' Clie Nt_ready_to_recv ': Conn.send (Cmd_result) #数据传输 conn.close ()

Socket-client2

  #!/usr/local/env Python3 "author:@ South Africa Bobo blog:http://www.cnblogs.com/songqingbo/e-mail:[email  Protected] "Import Socketip_port = (" 127.0.0.1 "," ssh_client "= Socket.socket () ssh_client.connect (Ip_port) while        True:user_input = Input ("ssh-client:"). Strip () If Len (user_input) = = 0:continue if user_input = ' Q ': Break Ssh_client.send (Bytes (user_input, ' UTF8 ')) #ack_msg = B "cmd_result_size|%s"% len (cmd_result) Server_ac    K_msg = SSH_CLIENT.RECV (+) cmd_res_msg = str (Server_ack_msg.decode ()). Split ("|") If cmd_res_msg[0] = = "Cmd_result_size": cmd_res_size = Int (cmd_res_msg[1]) ssh_client.send (b "client_ready_to _recv ") res = ' Received_size = 0 while received_size < Cmd_res_size:server_data = SSH_CLIENT.RECV (50 0) Received_size + = Len (server_data) Res + = str (Server_data.decode ()) Else:print (res) prin T ("-----------recv Don----------") ssh_client.close ()  

Python Development Learning-day07 (object-oriented polymorphism, class method, reflection, new class and Legacy class, socket programming)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.