Python-day7

1.类方法classmethod

#!/usr/bin/env python3
# this is CR7 scripts!

class test(object):
    name = "Jay"
    def __init__(self,name):
        self.NAME = name

    @classmethod
    def talk(cls):
        print("%s !!"%  cls.name)


o1 = test("Charlie")
o1.talk()
###########################################
Jay !!

注:用法很简单,强制的限制调用者调用方法时只能读取类的变量而不能调用构造函数的变量

2.属性方法

#!/usr/bin/env python3
# this is CR7 scripts!

class test(object):
    name = "Jay"
    def __init__(self,name):
        self.NAME = name

    @property
    def talk(self):
        print("%s ! !"% self.NAME)

o1 = test("charlie")
o1.talk
######################################
charlie ! !

注:把一个方法变成静态属性

3.属性方法三部曲

#!/usr/bin/env python3
# this is CR7 scripts!

class test(object):
    name = "Jay"
    def __init__(self,name):
        self.NAME = name
        self.__FOOD = None

    @property
    def talk(self):
        print("%s :"% self.NAME,self.__FOOD)

    @talk.setter
    def talk(self,what):
        self.__FOOD = what

    @talk.deleter
    def talk(self):
        del self.__FOOD
        print("删完了")

o1 = test("charlie")
o1.talk = "baozi"
o1.talk
del o1.talk
#################################################
charlie : baozi
删完了

注:作用就是给属性方法传值,然后通过del删除静态属性的值,但是应用场景呢?请看下文:

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    def __init__(self,name):
        self.flight_name = name


    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  1

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")

    @flight_status.setter
    def flight_status(self,value):
        print("%s has change %s"%(self.flight_name,value))


f = Flight("CA980")
f.flight_status
f.flight_status = 2
######################################
checking flight CA980 status 
flight is arrived...
CA980 has change 2

注:想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

  1. 连接航空公司API查询

  2. 对查询结果进行解析

  3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以,明白了么?

4.描述信息

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    '''这是描述飞机的'''
    def __init__(self,name):
        self.flight_name = name

print(Flight.__doc__)
#################################
这是描述飞机的

5.其他方法

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    def __init__(self,name):
        self.flight_name = name



o1 = Flight("charlie")
print(o1.__module__)
####################################
__main__

注:来自主函数

6.call方法

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    def __init__(self,name):
        self.flight_name = name
    def __call__(self, *args, **kwargs):
        print(*args,**kwargs)


Flight("charlie")(1231,123123)
############################################
1231 123123

注:call方法的调用方式就是类名后面直接+ (),应用场景下文会讲到

7.dict方法

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    def __init__(self,name):
        self.flight_name = name
    def __call__(self, *args, **kwargs):
        print(*args,**kwargs)

print(Flight.__dict__)

o1 = Flight("charlie")
print(o1.__dict__)
##############################################
{'__module__': '__main__', '__init__': <function Flight.__init__ at 0x000000000284DF28>, '__call__': <function Flight.__call__ at 0x0000000002852048>, '__dict__': <attribute '__dict__' of 'Flight' objects>, '__weakref__': <attribute '__weakref__' of 'Flight' objects>, '__doc__': None}
{'flight_name': 'charlie'}

注:列出所有成员和变量

8.str方法

#!/usr/bin/env python3
# this is CR7 scripts!

class Flight(object):
    def __init__(self,name):
        self.flight_name = name


    def __str__(self):
        return self.flight_name


o1 = Flight("charlie")
print(o1)
##################################
charlie

9.__new方法

#!/usr/bin/env python3
# this is CR7 scripts!

class test(object):
    def __init__(self,name,age):
        self.NAME = name
        self.AGE = age
        print("init")

    def __new__(cls, *args, **kwargs):
        print("new")
        return object.__new__(cls)

o1 = test("charlie",22)
###########################################
new
init

注:new方法也会在生成对象的时候执行,而且执行顺序优先于构造函数

10.__new函数解释

#!/usr/bin/env python3
# this is CR7 scripts!

class test(object):
    def __init__(self,name,age):
        self.NAME = name
        self.AGE = age
        print("init")

    def __new__(cls, *args, **kwargs):
        print("new")
        #return object.__new__(cls)

o1 = test("charlie",22)
#############################################
new

注:说明了类是如何实例化的,所有的类实例化的时候其实是通过new方法去调用init构造函数,从而实现初始化实例的操作!如果以后在定制类的时候需要在实例化对象之前加入一些操作,就可以自定义修改new方法,上文中return object.new(cls)的意思是继承父类中的new方法,进行实例化,和super不同的是·,super是继承了之后要修改,而object是直接继承调用,而此时需要传入参数,需要把test这个类(因为类本身也是个对象)当作参数穿进去,所以cls的作用其实就是self,也就代指test和o1

11.反射1

#!/usr/bin/env python3
# this is CR7 scripts!

class dog(object):
    def __init__(self,name):
        self.NAME = name

    def eat(self,food):
        print("%s is eating %s"%(self.NAME,food))


o1 = dog("bill")
funcx = input(">>:")
if hasattr(o1,funcx):
    func = getattr(o1,funcx)
    func("fish")
#######################################################
>>:eat
bill is eating fish

注:用户输入的方式传参调用类方法

12.反射2

#!/usr/bin/env python3
# this is CR7 scripts!

def bulk(self):
    print("%s is wang...!!!"%self.NAME)

class dog(object):
    def __init__(self,name):
        self.NAME = name

    def eat(self,food):
        print("%s is eating %s"%(self.NAME,food))


o1 = dog("bill")
funcx = input(">>:")
if hasattr(o1,funcx):
    func = getattr(o1,funcx)
    func("fish")
else:
    setattr(o1,funcx,bulk)
    o1.bulk(o1)
###################################################
>>:bulk
bill is wang...!!!

注:把方法加入到类中去调用,但是需要自己把self参数传进去

13.反射3

#!/usr/bin/env python3
# this is CR7 scripts!

def bulk(self):
    print("%s is wang...!!!"%self.NAME)

class dog(object):
    def __init__(self,name):
        self.NAME = name

    def eat(self,food):
        print("%s is eating %s"%(self.NAME,food))


o1 = dog("bill")
funcx = input(">>:")
if hasattr(o1,funcx):
    func = getattr(o1,funcx)
    func("fish")
else:
    setattr(o1,funcx,22)
    print(getattr(o1,funcx))
####################################################
>>:money
22

注:动态加入一个属性,如果输入的字符在类中找不到对应的属性的话

14.反射4

#!/usr/bin/env python3
# this is CR7 scripts!

def bulk(self):
    print("%s is wang...!!!"%self.NAME)

class dog(object):
    def __init__(self,name):
        self.NAME = name

    def eat(self,food):
        print("%s is eating %s"%(self.NAME,food))


o1 = dog("bill")
funcx = input(">>:")
if hasattr(o1,funcx):
    #attr = getattr(o1,funcx)
    setattr(o1,funcx,"dadadada")
else:
    setattr(o1,funcx,22)
    print(getattr(o1,funcx))

print(o1.NAME)
######################################################
>>:NAME
dadadada

注:如果属性已存在,那么可以修改值

14.反射5

#!/usr/bin/env python3
# this is CR7 scripts!

def bulk(self):
    print("%s is wang...!!!"%self.NAME)

class dog(object):
    def __init__(self,name):
        self.NAME = name

    def eat(self,food):
        print("%s is eating %s"%(self.NAME,food))


o1 = dog("bill")
funcx = input(">>:")
if hasattr(o1,funcx):
    delattr(o1,funcx)
else:
    setattr(o1,funcx,22)
    print(getattr(o1,funcx))

print(o1.NAME)
################################################
>>:NAME
Traceback (most recent call last):
  File "C:/Users/dabin/PycharmProjects/dabin/day7/test.py", line 23, in <module>
    print(o1.NAME)
AttributeError: 'dog' object has no attribute 'NAME'

注:删除变量

15.异常处理

#!/usr/bin/env python3
# this is CR7 scripts!

data = [1,2]

try:
    data[3]
except IndexError as e:
    print("without",e)
################################
without list index out of range

注:列表异常处理

16.异常处理2

#!/usr/bin/env python3
# this is CR7 scripts!

data = [1,2]

try:
    data[3]
    open('123.txt')
except Exception as e:
    print("without",e)
########################
without list index out of range

注:一并处理错误,但是只要遇到第一个错,就不会继续往下执行,需要自行判断错误类型

17.异常处理3

#!/usr/bin/env python3
# this is CR7 scripts!

data = [1,2]



try:
    data[3]
    open('123.txt')
except IndexError as e:
    print("index",e)
except KeyError as e:
    print("key",e)
except Exception as e:
    print("except!!")
else:
    print("一切正常")
finally:
    print("不管有没有错,都执行")
###############################
index list index out of range
不管有没有错,都执行

注:else指如果没有报错那么执行,finally指不管怎么样都会执行

18.自定义异常处理

#!/usr/bin/env python3
# this is CR7 scripts!

class charliefalse(Exception):
    def __init__(self,msg):
        self.MSG = msg

    # def __str__(self):
    #     return "777"

try:
    raise charliefalse('database is disconnected!')
except charliefalse as e:
    print(e)
##########################################################
database is disconnected!

注:raise意思是手动触发

网络编程socket

1.server端

#!/usr/bin/env python3
# this is CR7 scripts!

import socket

#1.声明协议类型
server = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket连接对象

#2.绑定监听端口
server.bind(('localhost',6969))

#3.监听端口(还没开始)
server.listen()

#等待连接
#server.accept()
#不能用server的原因是如果客户端是来自多个地址,那么服务器就不知道到底具体是哪个地址,就好比电话的多个电话打入,无法切换到具体的线路上
#conn是对方打进来的一个链接,一个实例,addr是地址
conn,addr = server.accept()
#conn就是客户端连过来而服务器端为其生成的一个连接实例

#接受数据大小
data = conn.recv(1024)

print("from client:",data)
#返回客户端信息

#发送给客户端的数据
conn.send(b"yesyes")

server.close()
#################################################
from client: b'Hello,World!'

注:Python3开始所有数据的发送都必须以二进制比特流的方式传送

2.client端

#!/usr/bin/env python3
# this is CR7 scripts!

import socket

#1.声明协议类型
client = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket链接对象

#2.连接
client.connect(('localhost',6969))

#3.发数据
client.send(b'Hello,World!')

#接受服务器的返回,声明数据大小,单位字节
data = client.recv(1024)

print("from server:",data)

client.close()
########################################
from server: b'yesyes'

3.发送以及接受中文信息

server:
#!/usr/bin/env python3
# this is CR7 scripts!

import socket

#1.声明协议类型
server = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket链接对象

#2.绑定监听端口
server.bind(('localhost',6969))

#3.监听端口(还没开始)
server.listen()

#等待连接
#server.accept()
#不能用server的原因是如果客户端是来自多个地址,那么服务器就不知道到底具体是哪个地址,就好比电话的多个电话打入,无法切换到具体的线路上
#conn是对方打进来的一个链接,一个实例,addr是地址
conn,addr = server.accept()
#conn就是客户端连过来而服务器端为期生成的一个连接实例

#接受数据大小
data = conn.recv(1024)

print("from client:",data.decode())
#返回客户端信息

#发送给客户端的数据
conn.send(b"yesyes")

server.close()

client:
#!/usr/bin/env python3
# this is CR7 scripts!

import socket

#1.声明协议类型
client = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket链接对象

#2.连接
client.connect(('localhost',6969))

#3.发数据
client.send('我要开始打电话了!!!'.encode())

#接受服务器的返回,声明数据大小,单位字节
data = client.recv(1024)

print("from server:",data)

client.close()

注:中文需要加码解码,无法直接b,需要encode以及decode

4.模拟ssh

server:
#!/usr/bin/env python3
# this is CR7 scripts!

import socket,subprocess

#1.声明协议类型
server = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket链接对象

#2.绑定监听端口
server.bind(('localhost',6969))

#3.监听端口(还没开始),如果写了数字那就是最大允许多少个链接
server.listen()

#等待连接
#server.accept()
#不能用server的原因是如果客户端是来自多个地址,那么服务器就不知道到底具体是哪个地址,就好比电话的多个电话打入,无法切换到具体的线路上
#conn是对方打进来的一个链接,一个实例,addr是地址
while True:
    conn,addr = server.accept()
    #conn就是客户端连过来而服务器端为期生成的一个连接实例

    #接受数据大小
    while True:
        data = conn.recv(1024)
        if not data:
            print("client is lost!")
            break
        #print("from client:",data.decode())
        #返回客户端信息
        result = subprocess.getstatusoutput(data)
        #发送给客户端的数据
        conn.send(result[1].encode())


server.close()

client:
#!/usr/bin/env python3
# this is CR7 scripts!

import socket

#1.声明协议类型
client = socket.socket() #默认不写类型就是IPV4,TCP协议,同时生成socket链接对象

#2.连接
client.connect(('localhost',6969))

#3.发数据
while True:
    msg = input("Please input your information,q[quit]: ").strip()
    if len(msg) == 0:
        continue
    elif msg == "q":
        break
    else:
        client.send(msg.encode())
        #接受服务器的返回,声明数据大小,单位字节
        data = client.recv(10240000)
        print(data.decode())

client.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值