本节目录
1、抽象接口2、静态方法、类方法、属性方法3、类的特殊方法 3.1 __doc__ 表示类的描述信息(注释) 3.2 __module__ 和 __class__ 3.3 __init__ 构造方法,通过类创建对象时,自动触发执行。 3.4 __del__ 3.5 __call__ 对象后面加括号,触发执行 3.6 __dict__ 查看类或对象中的所有成员 3.7 __str__ 3.8 __getitem__、__setitem__、__delitem__ 3.9 __new__ \ __metaclass__4、异常处理 4.1 基本结构 4.2 完整结构 4.3 断言 4.4 自定义异常5、反射
1、抽象接口
py2写法:import abcclass Alert(object):'''报警基类'''__metaclass__ = abc.ABCMeta #必须实现子类实例化和调用send必须重写send,否则报错@abc.abstractmethoddef send(self):'''报警消息发送接口'''passclass MailAlert(Alert):passm = MailAlert()m.send()py3写法:不重写则报错class Alert(object):'''报警基类'''def send(self):'''报警消息发送接口'''raise NotImplementedErrorclass MailAlert(Alert):
passm = MailAlert()
m.send()报错:F:\Python\Python3\python.exe D:/python培训/our_python/day8/抽象接口.pyTraceback (most recent call last):File "D:/python培训/our_python/day8/抽象接口.py", line 12, in <module>m.send()File "D:/python培训/our_python/day8/抽象接口.py", line 6, in sendraise NotImplementedErrorNotImplementedError正确写法:class Alert(object):'''报警基类'''def send(self):'''报警消息发送接口'''raise NotImplementedErrorclass MailAlert(Alert):
def send(self,msg):print("__send__", msg)m = MailAlert()
m.send("sssss")输出:__send__ sssss2、静态方法、类方法、属性方法
#静态方法即不能访问公有属性也不能访问实例#类方法只能访问公有属性,不能访问实例#属性方法,把一个方法编程一个静态属性,直接访问这个方法、但不能调用这个方法测试:class Person(object):name = "class_jack"def __init__(self,name):self.name = name@staticmethod #静态方法即不能访问公有属性也不能访问实例
def eat(name,food):print("%s is eating..%s" % (name,food))@classmethod #类方法只能访问公有属性,不能访问实例def walk(self):print("%s is walking..." % self.name)@property #属性方法,把一个方法编程一个静态属性def talk(self):print("%s says "% self.name)@talk.setter #修改属性def talk(self,C_name):self.name = C_nameprint("%s says " % self.name)@talk.deleter
def talk(self):print("del %s says " % self.name)
p = Person("jack")
p.eat("xiaoming","noodle") #静态方法,传入自己的变量
p.walk() #直接访问类变量p.talk #直接访问,但不能使用p.talk ()调用p.talk = "TTT" #修改属性del p.talk #删除属性 属性方法应用--航班查询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, status):status_dic = { 0: "canceled",1: "arrived",2: "departured"}print("\033[31;1mHas changed the flight status to \033[0m", status_dic.get(status))@flight_status.deleter # 删除属性
def flight_status(self):print("status got removed...")f = Flight("CA980")
f.flight_statusf.flight_status = 2 #触发@flight_status.setterf.flight_statusdel f.flight_status #触发@flight_status.deleterf.flight_status3、类的特殊方法
3.1 __doc__ 表示类的描述信息(注释)print(f.__doc__)3.2 __module__ 和 __class__
__module__ 表示当前操作的对象在那个模块__class__ 表示当前操作的对象的类是什么print(f.__module__)__main__print(f.__class__)<class '__main__.Flight'>3.3 __init__ 构造方法,通过类创建对象时,自动触发执行。
3.4 __del__3.5 __call__ 对象后面加括号,触发执行def __call__(self, *args, **kwargs):print("__call:",args,kwargs)输出:__call: ('sssss',) {}3.6 __dict__ 查看类或对象中的所有成员
print(f.__dict__)输出:{'flight_name': 'CA980'}3.7 __str__
如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值def __str__(self):return "<flight:%s,status:%s>" %(self.flight_name,self.flight_status)输出:<flight:CA980,status:None>3.8 __getitem__、__setitem__、__delitem__
def __getitem__(self, key):print('__getitem__', key)def __setitem__(self, key, value):
print('__setitem__', key, value)def __delitem__(self, key):
print('__delitem__', key)st = f['CA980'] #触发__getitem__f['CA980'] = 1 #触发__setitem__del f['CA980'] #触发__delitem__输出:__getitem__ CA980 __setitem__ CA980 1 __delitem__ CA9803.9 __new__ \ __metaclass__
其他资料:https://zhuanlan.zhihu.com/p/23887627class Foo(object):def __init__(self,name):self.name = namef = Foo("alex")print type(f) # 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类创建print type(Foo) # 输出:<type 'type'> 表示,Foo类对象由 type 类创建自建一个类(动态创建类):
def talk(self,msg):print("%s is talking: %s" % (self.name,msg))def __init__(self,name):self.name = nameDog = type("Dog",(object,),{"talk":talk,"__init__":__init__})print(Dog)
print(type(Dog))d = Dog("xiaoming")print(type(d))d.talk("wwwwww")输出:
<class '__main__.Dog'><class 'type'><class '__main__.Dog'>xiaoming is talking: wwwwww 4、异常处理4.1 基本结构while True:try:print("1212")except Exception as e:print("Error")4.2 完整结构while True:try:print("1212")except Exception as e:print("Error")else:print("3434")finally:print("5656")4.3 断言
assert 条件条件为True则继续,否则主动抛出异常 4.4 自定义异常class TTTError(Exception):def __init__(self,message):self.msg = messagesuper(TTTError,self).__init__(message)try:
name = "Alex"if name != "TTT":raise TTTError("你不是TTT") #主动抛出错误except TTTError as e:print("TTTError",e)except Exception as e:print(e,111111)输出:TTTError 你不是TTT5、反射
cat account
def login():return "请输入用户名、密码"def logout():return "跳转到登录界面"from controller import account
while True:action = input(">>:")if (hasattr(account,action)):func = getattr(account,action)result = func()else:result = '404'print(result)输出:F:\Python\Python3\python.exe D:/python培训/our_python/day8/app.py>>:login请输入用户名、密码>>:logout跳转到登录界面>>:asd404