day9学python

本章总结:

1.类

2.异常处理

3.socket 网络编程

===========================================================

类的特点:

1.封装-同其他语言

2.继承

py2 经典类深度优先 新式类类名(object)广度优先
py3 都是广度优先

3.多态-python本身无多态 可用方法调用

类:

class 类名(object):    //有括号即为新式类名(现在多用此种)

  code

构造函数:          //用作初始化

 def __init__(self,属性):

  self.属性=属性

示例

class Role:
    n = 1       #类变量(节省内存)
    lis=[]
    def __init__(self,name,role,weapon,life_value=100,money=100):

        #构造函数
        self.name=name
        self.role=role
        self.weapon=weapon
        self.__life_value=life_value    #私有属性 只有靠方法调用显示
        self.money=money

    def get(self):
        print(self.__life_value)
    def set(self,life):
        self.__life_value=life
    def __shot(self):           #私有方法 (在前面加__)
        print(self.name,"射击!")
    def __del__(self):  #析构函数(关闭打开的临时文件)
        print(self.name,"is dead")

继承:

使子类能使用父类的属性与方法,并在其上重载方法(加功能)

class 子类名(父类名):

  code

当有属性要增加时 必须重载构造函数(不写 则直接调用父类构造函数)

def __init__(self,子类属性):
        super(子类名,self).__init__(父类所有属性)
        self.子类属性=子类属性

例如:

class cat(animal):
    def __init__(self,name,age,size):
        super(cat, self).__init__(name,age)
        self.size=size

多态

当多个类都拥有相同方法,但内部都有所区别时,可用多态减少代码量

class animal(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age

class dog(animal):
    def __init__(self,name,age,color):
        super(dog,self).__init__(name,age)
        self.color=color

    def talk(self):
        print(self.name,"is barking")

class cat(animal):
    def __init__(self,name,age,size):
        super(cat, self).__init__(name,age)
        self.size=size

    def talk(self):
        print(self.name,"is miaomiaoing")

d=dog("lala",12,"")
c=cat("nana",21,"")

def nimal(obj):
   obj .talk();
nimal(c)
nimal(d)

两个类-cat和dog都有talk()方法 但其中内容有所不同

此时 利用nimal(obj)去传入实例化对象 达到简化代码的效果

反射

1.hasattr(d,choice)   //判断d对象中是否有对应的函数 boolean形 有choice的函数则为true
2.getattr(d,choice)   //根据choice去调用d中的函数 
3.setattr(x,y,z)    // x.y=z 自定义创建类中的对象

##其中d为实例化对象 choice为用户输入的字符串

例:

if(hasattr(d,choice)):     #判断d对象中是否有对应的函数 boolean形 有choice的函数则为true
      func=getattr(d,choice) #根据choice去调用d中的函数    
      func()
   setattr(x,y,z) #   x.y=z    自定义创建类中的对象

=======================================================

异常处理

代码示例==

try:
      code
 except(error1,error2) as e: 
     print e
 except exception as e  //用于最后 抓住所有其他错误
 else:
       print(“无错误执行”)
 finally:
       print("无论有没有错都执行")
 
特殊注意: 此处抓取异常用except关键词!
 
===========================================================

 Socket网络编程

实现双方通信 client和server

#首先要想实现 保证两者端口相对应

client的代码实现

import socket

client=socket.socket()  #声明socket类型,同时生成socket连接对象
client.connect(("localhost",123))#端口#ip和端口两个数据 但connect只接受一个参数用元组
while True:
    
  mas=input(">>>:")    #用户输入要传递的信息
   if(len(mas)==0):
         continue

    client.send(mas.encode("utf-8"))    #所有数据传输接收都用byte格式

    data=client.recv(1024)      #此处为对方接受到信息后的回复( 收多少数据)

    print("recv:",data.decode())
client.close()

server的代码实现

import socket

server=socket.socket()
server.bind(("localhost",123))#绑定端口
server.listen()     #监听端口
print("waiting...............")
    while True:
        #等待电话
        conn,addr=server.accept()      #返回值两个(conn来电实例,addr来电地址)
        print("phone coming!")
        while True:

            data=conn.recv(1024)   #接受来电的信息
            print(data.decode())  #此处data为二进制代码 需要解码

            if not data:
                print("client has lost.....")
                break

            conn.send(data.upper())#收到消息后返还大写

server.close()

此时 实现了 client与server的通信

client发送断开后

server可接受下个 信号指令 实现打电话1-1 挂电话后下一个接上的效果

下面给出自己附加的文件传输代码 :

client

import socket
client=socket.socket()  client.connect(("localhost",123))
f1=open("doc","r",encoding="utf-8")
for line in f1:
    print(line)
   #所有数据传输接收都用byte格式
client.close()

server:

import socket

server=socket.socket()
server.bind(("localhost",123))server.listen()  
print("waiting...............")
with open("copy", "a", encoding="utf-8") as f2:
    while True:

        conn,addr=server.accept()        
        print("phone coming!")
        while True:

            data=conn.recv(1024) 
            f2.write(data.decode())        #写入文件以字符串形式
            print(data.decode())

            if not data:
                print("client has lost.....")
                break
server.close()

猜你喜欢

转载自www.cnblogs.com/cc123nice/p/10547107.html