Python学习day7
一、静态方法
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
#Author:Fred
class Dog(object):
def __init__(self,name):
self.name = name
@staticmethod #实际上和类没有关系了,不怎么用
def eat(self):
print("%s is eating %s"%(self.name,'dd'))
d = Dog("陈荣华")
d.eat(d)
二、类方法
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
# Author:Fred
class Dog(object):
name = "alex"
def __init__(self, name):
self.name = name
@classmethod #类方法只能访问类变量,不能访问实例变量,不怎么用
def eat(self):
print("%s is eating %s" % (self.name, 'dd'))
def talk(self):
print("%s is talking"%self.name)
d = Dog("陈荣华")
d.eat()
#d.talk()
三、属性方法
属性方法的作用就是通过@property把一个方法变成一个静态属性
# Author:Fred
class Dog(object):
'''这个类是描述狗这个对象的'''
name = "alex"
def __init__(self, name):
self.name = name
@property #属性方法,把一个方法变成一个静态属性
def eat(self):
print("%s is eating %s" % (self.name, 'dd'))
@eat.setter
def Eat(self, food):
print("set to food:", food)
def talk(self):
print("%s is talking" % self.name)
def __call__(self, *args, **kwargs):
print("running call",args,kwargs)
def __str__(self): #__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
return "<obj:%s>" %self.name
#print(Dog.__dict__)#字典形式打印类里的所有属性,不包括实例属性
#print(Dog.__doc__)
d = Dog("陈荣华")
print(d)
#print(d.__dict__)#字典形式打印类里的实例属性,不包括类属性
# d(1,2,3,name=333)
# d.eat #调用不能有参数了
# d.Eat = "baozi"
通过定义静态属性来实现的,比如,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
1. 连接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户
因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以:
#Author:Fred
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 2
@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,status):
print("flight %s has changed status to %s" %(self.flight_name,status))
f = Flight("CA980")
f.flight_status
f.flight_status = 2
四、类的特殊成员方法
#Author:Fred
class MyType(type):
def __init__(self,*args,**kwargs):
print("Mytype __init__",*args,**kwargs)
def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj
def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)
print('here...')
class Foo(object,metaclass=MyType):
def __init__(self,name):
self.name = name
print("Foo __init__")
def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)
f = Foo("Alex")
print("f",f)
print("fname",f.name)
五、反射
#Author:Fred
'''
hasattr(obj,name_str),判断一个对象obj里是否有对应的name_str字符串的方法
getattr(obj,name_str),根据字符串去获取obj对象里的对应的内存地址
setattr(obj,'y',z),相当于x.y = v
delattr()
'''
def bulk(self):
print("%s is yelling..."%self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating..."%self.name,food)
d = Dog("Alex")
choice = input(">>:").strip()
if hasattr(d,choice): #判断有没有
#delattr(d,choice)
getattr(d,choice)
else:
# setattr(d,choice,bulk)
# d.bulk(d)
setattr(d,choice,None)
v = getattr(d,choice)#d.choice此时是一个字符串不能直接调用
print(v)
print(d.name)
六、异常处理
1.#Author:Fred
names = ['alex','jack']
data = {}
try:
# names[3]
# data['name']
open("tes.txt")
except KeyError as e:
print("没有这个key",e)
except IndexError as e:
print("列表操作错误",e)
except Exception as e:
print("未知",e)
else:
print("一切正常")
finally:
print("不管有没有错都执行")
- 自定义异常
#Author:Fred
class WupeiqiException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
# name = []
# name[3]
raise WupeiqiException('我的异常') #触发
except WupeiqiException as e:
print(e)
七、Socket 编程
1.socket_server.py:
#Author:Fred
import socket
server = socket.socket()
server.bind(('localhost',6969)) #绑定要监听的端口
server.listen() #监听
print("开始等电话")
conn,addr = server.accept() #等电话打进来
print(conn,addr) #coon就是客户端连过来而在服务器端为其生成的一个链接实例
print("电话打进来了")
while True:
data = conn.recv(1024)
print("recv:",data)
conn.send(data.upper())
server.close()
2.socket_client.py:
#Author:Fred
import socket
client = socket.socket() #声明socket类型,同事生成socket连接对象
client.connect(('localhost',6969))
while True:
msg = input(">>:").strip()
if len(msg) == 0:continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print("recv:",data.decode())
client.close()

浙公网安备 33010602011771号