1.反射
2.异常处理
3.动态导入模块
4.抽象类
5.网络编程socket
6.静态,动态创建类案例
1.反射
通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法
getattr(object, name, default=None)
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
hasattr(object,name)
判断object中有没有一个name字符串对应的方法或属性
setattr(x, y, v)
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
delattr(x, y)
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """
反射代码案例
class Foo(object):
def __init__(self):
self.name = "zongyimin"
def func(self):
return "func"
obj = Foo()
# #### 检查是否含有成员 ####
hasattr(obj, 'name')
hasattr(obj, 'func')
# #### 获取成员 ####
getattr(obj, 'name')
getattr(obj, 'func')
# #### 设置成员 ####
setattr(obj, 'age', 18)
setattr(obj, 'show', lambda num: num + 1)
# #### 删除成员 ####
delattr(obj, 'name')
delattr(obj, 'func')
2.动态导入模块
import
importlib
__import__
(
'import_lib.metaclass'
)
#这是解释器自己内部用的
#importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个
3.异常处理
#_*_coding:utf-8_*_
"""
异常处理:在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,
而是一个提示的页面,通俗来讲就是不让用户看见大黄页!
"""
import sys
import os
# while True:
# num1 = input(">>:")
# num2 = input(">>:")
# try:
# num1 = int(num1)
# num2 = int(num2)
# result = num1+num2
# except Exception as e:
# print(e)
# print("错误")
"""
异常种类:
AttributeError 试图访问一个对象没有的属性
IOError 输入、输出异常,基本上无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误,缩进问题
IndexError 索引错误
KeyError 试图访问字典里不存在的键
KeyboardInterrupt ctrl+c被按下
NameError 使用一个还未被赋值的对象变量
SyntaxError Python 代码非法
TypeError 类型错误
UnboundLocalError 试图访问一个未被赋值的局部变量
ValueError 传入一个调用者不期望的值
"""
dic = ["zongyimin"]
try:
dic[10]
except IndexError as e:
print(e)
dic = {"key":"value"}
try:
dic["key1"]
except KeyError as e:
print(e)
s1 = "hello"
try:
int(s1)
except Exception as e:
print(e)
try:
#主代码块
pass
except KeyError as e:
#异常时,执行该模块
pass
else:
#主代码模块执行完,执行该模块
pass
finally:
#无论异常与否,最终执行该模块
pass
"""主动触发异常"""
try:
raise Exception("错误")
except Exception as e:
print(e)
"""自定义异常"""
class zongyiminException(Exception):
def __init__(self,msg):
self.message = msg
def __str__(self): #如何一个类中定义了__str__方法,那么打印对象时,默认输出该方法的返回值
return self.message
try:
raise zongyiminException("自定义异常")
except zongyiminException as e:
print(e)
"""断言"""
# assert 条件
assert 1==1
try:
assert 1==2
except AssertionError as e:
print(e)
"""断言"""
# assert 条件
assert 1==1
try: assert 1==2
except AssertionError as e:
print(e)
4.网络编程
服务端:
import socket
server =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(("0.0.0.0",8000))
server.listen(5)
print("listen is ready")
while True:
conn,client_addr = server.accept() #阻塞直到有客户端连接
print(conn,client_addr)
while True:
try:
data = conn.recv(1024)
print("+",data)
conn.send(b"get your msg")
except ConnectionResetError as e:
print(e)
break
客户端:
import socket client = socket.socket() client.connect(("localhost",8000)) while True: msg = input(">>").strip() if len(msg) == 0 :continue client.send(msg.encode()) data = client.recv(1024) print(data)
5.抽象类案例
# -*- coding:utf-8 -*- """抽象类案例""" class Alert (object): #父类定义send函数,继承它的子类必须重新定义方法 """报警基类""" def send(self): # pass raise NotImplementedError # def send(self): # exit("没有定义方法") class MailAlter(Alert): def send(self,msg): #子类中必须定义方法 print("sdasdasda",msg) pass # pass class SendAlter(Alert): pass m = MailAlter() m.send("name")
6.动态创建类案例
"""静态创建类""" class Foo(object): def __init__(self,name): self.name = name f = Foo("zongyimin") print(type(f)) print(type(Foo))
#使用云类type()动态创建类 def func(self): print("helllo word") Foo = type("Foo",(object,),{"func":func}) #动态创建类 print(Foo) print(type(type))
要创建一个class对象,
type()
函数依次传入3个参数:
- class的名称;
- 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
- class的方法名称与函数绑定,这里我们把函数
fn
绑定到方法名hello
上。通过
type()
函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()
函数创建出class。正常情况下,我们都用
class Xxx...
来定义类,但是,type()
函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。