python異常(高級) Exception

異常(高級) Exception

  異常回顧:
    try-except 語句 捕獲(接收)異常通知,把異常流程變為正常流程
    try-finally 語句 執行必須要執行的語句.
    raise 語句 發送異常通知,同時進入異常流程
    assert 語句 發送AssertionError異常
    with 語句

with語句
  語法:
    with 表達式1 [as 變量1], 表達式2 [as 變量2], ...:
      語句塊
  作用:
  使用于對資源進行訪問的場合,確保使用過程中不管是否發生異常都會執行必要的清理操作,并釋放資源
  如: 文件使用后自動關閉,線程中鎖的自動獲取和釋放等

  try:# file = open("../day19.txt")with open('../day19.txt') as file:line1 = file.readline()print("第一行內容是:", line1)n = int(line1) # with語句保證在出異時,文件也能被關閉print(n)except OSError:print("文件打開失敗")except ValueError:print('讀寫文件時出錯')
View Code

說明:
  with語句同try-finally語句一樣,不會改變程序的狀態(異常或正常狀態)?

環境管理器:
  類內有'__enter__' 和 '__exit__' 實例方法的類被稱為環境管理器能夠用with語句進行管理的對象必須是環境管理器
  __enter__將在進入with語句之前被調用,并返回由as 變量管理的對象
  __exit__ 將在離開with語句時被調用,且可以用參數來判斷在離開with語句時是否有異常發生并做出相應的處理

  class A:def __enter__(self):print("__enter__方法被調用")# 此處打開文件return self # self 將被with as后的變量綁定def __exit__(self, exc_type, exc_val, exc_tb):print("__exit__方法被調用")# 此處關閉文件if exc_type is None:print("正常離開with語句")else:print("異常離開with語句")print(exc_type, exc_val, exc_tb)try:with A() as a:print("這是with內的語句")err = ValueError("故意拋出一個錯誤")raise errexcept ValueError:print("with語句內出現異常!!")
View Code

異常類:
  BaseExcetion 類是一切異常類的基類
  自定義的異常類型必須直接或間接的繼承自BaseExcetion類

運算符重載
  讓自定義的類生成的對象(實例) 能夠使用運算符進行操作

  作用:
    讓自定義類的實例像內建對象一樣進行運算符操作
    讓程序簡潔易讀
    對自定義對象將運算符賦予新的運算規則

  說明:
    運算符已經有固定的含義,不建議改變原有運算符的含義
  方法名          運算符和表達式    說明
  __add__(self, rhs)    self + rhs      加法
  __sub__(self, rhs)    self - rhs      減法
  __mul__(self, rhs)    self * rhs      乘法
  __truediv__(self, rhs)  self / rhs      除法
  __floordiv__(self, rhs)  self // rhs      地板除法
  __mod__(self, rhs)    self % rhs      求余
  __pow__(self, rhs)    self ** rhs      冪運算

  rhs (right hand side)   右手邊

二元運算符的重載方法:
  def __xxx__(self, other):
    ...

  class MyNumber:def __init__(self, value):self.data = valuedef __repr__(self):return "MyNumber(%d)" % self.datadef __add__(self, other):temp = self.data + other.dataobj = MyNumber(temp) # 創建一個新的對象return objdef __sub__(self, other):temp = self.data - other.dataobj = MyNumber(temp) # 創建一個新的對象return objn1 = MyNumber(100)n2 = MyNumber(200)# n3 = n1.__add__(n2)
n3 = n1 + n2 # 等同于 n3 = n1.__add__(n2)print(n1, "+", n2, '=', n3)n4 = n1 - n2print(n1, "-", n2, '=', n4)
View Code

反向算術運算符的重載
  當運算符的左側為內建類型時,右側為自定義類的對象進行算術運算符運算時,會出現TypeError錯誤,因無法修改內建類型的代碼來實現運算符重載,此時需要反向算術運算符重載

方法如下:
  方法名           運算符和表達式    說明
  __radd__(self, lhs)   ?lhs + self      加法
  __rsub__(self, lhs)    lhs + self      減法
  __rmul__(self, lhs)    lhs * self      乘法
  __rtruediv__(self, lhs)  lhs / self      除法
  __rfloordiv__(self, lhs)  lhs // self      地板除法
  __rmod__(self, lhs)    lhs % self      求余
  __rpow__(self, lhs)    lhs ** self      冪運算

  lhs (left hand side)    左手邊

  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __add__(self, rhs):L = self.data + rhs.datareturn MyList(L)def __repr__(self):return "MyList(%s)" % self.datadef __mul__(self, rhs):L = self.data * rhsreturn MyList(L)def __rmul__(self, lhs):print("__rmul__被調用")return MyList(self.data * lhs)L1 = MyList(range(1, 4))L2 = MyList([4, 5, 6])L5 = L1 * 2 # L5 = L1.__mul__(2)print(L5) # MyList([1, 2, 3, 1, 2, 3])
L6 = 2 * L1 # L1.__rmul__(2) 2.__mul__(L1)print(L6) # ???
View Code

復合賦值算術運算符的重載
  以復合賦值算述運算符 x += y 主為例,此運算符會優先調用x.__iadd__(y) ,如果沒有__iadd__方法時,會將復合賦值運算符拆解為 x = x + y然后調用x = x.__add__(y)方法,如再不存在__add__方法,則會觸發TypeError錯誤
  其它復合賦值運算符有相同的規則

  方法名           運算符和表達式   說明
  __iadd__(self, rhs)    self += rhs    加法
  __isub__(self, rhs)    self -= rhs    減法
  __imul__(self, rhs)    self *= rhs    乘法
  __itruediv__(self, rhs)  self /= rhs    除法
  __ifloordiv__(self, rhs)  self //= rhs    地板除法
  __imod__(self, rhs)    self %= rhs    求余
  __ipow__(self, rhs)    self **= rhs    冪運算

  rhs (right hand side)   右手邊

  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __repr__(self):return "MyList(%s)" % self.datadef __add__(self, rhs):print("__add__")L = self.data + rhs.datareturn MyList(L)# def __iadd__(self, rhs):# print("__iadd__")# self.data += rhs.data# return self
L1 = MyList(range(1, 4))L2 = MyList([4, 5, 6])print("+= 之前的 id(L1)", id(L1))L3 = L1L1 += L2print("+= 之后的 id(L1)", id(L1))print(L1)print(L3)
View Code

比較運算符的重載
  方法名         運算符和表達式   說明
  __lt__(self, rhs)    self < rhs     小于
  __le__(self, rhs)    self <= rhs    小于等于
  __gt__(self, rhs)    self > rhs     大于
  __ge__(self, rhs)    self >= rhs    大于等于
  __eq__(self, rhs)    self == rhs    等于
  __ne__(self, rhs)    self != rhs    不等于

注: 比較運算符通常返回布爾值 True 或 False

位運算符的重載
  方法名          運算符和表達式  說明
  __and__(self, rhs)    self & rhs     位與
  __or__(self, rhs)     self | rhs    位或
  __xor__(self, rhs)    self ^ rhs    位異與
  __lshift__(self, rhs)   self << rhs    左移
  __rshift__(self, rhs)   self >> rhs    右移

反向位運算符的重載
  方法名          運算符和表達式  說明
  __rand__(self, lhs)    lhs & self    位與
  __ror__(self, lhs)    lhs | self    位或
  __rxor__(self, lhs)    lhs ^ self    位異與
  __rlshift__(self, lhs)  lhs << self    左移
  __rrshift__(self, lhs)  lhs >> self    右移

復合賦值位運算符的重載
  方法名          運算符和表達式   說明
  __iand__(self, rhs)    self &= rhs    位與
  __ior__(self, rhs)    self |= rhs    位或
  __ixor__(self, rhs)    self ^= rhs    位異與
  __ilshift__(self, rhs)  self <<= rhs    左移
  __irshift__(self, rhs)  self >>= rhs    右移


一元運算符的重載
  方法名        運算符和表達式  說明
  __neg__(self)    -self      負號
  __pos__(self)    +self      正號
  __invert__(self)   ~self       取反

一元運算符的重載語法:
  class 類名:
    def __xxx__(self):
      ...

  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __repr__(self):return "MyList(%s)" % self.datadef __neg__(self):return MyList([-x for x in self.data])L1 = MyList([1, -2, 3, -4, 5])L2 = -L1print(L2) # MyList([-1, 2, -3, 4, -5])
View Code

in , not in 運算符的重載
  方法名          運算符和表達式  說明
  __contains__(self, e)   e in self     成員運算

  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __repr__(self):return "MyList(%s)" % self.datadef __contains__(self, item):return item in self.dataL1 = MyList([1, -2, 3, -4, 5])if 3 in L1:print("")else:print("")print(3 not in L1)
View Code

索引和切片運算符的重載:
  重載方法
  方法名          運算符和表達式   說明
  __getitem__(self, i)   x = self[i]    索引/切片取值
  __setitem__(self, i, v) self[i] = v    索引/切片賦值
  __delitem__(self, i)   del self[i]    刪除索引/切片

作用:
  讓自定義的類型的對象能夠支持索引和切片操作

  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __repr__(self):return "MyList(%s)" % self.datadef __getitem__(self, item):print("__getitem__", item)return self.data[item]def __setitem__(self, key, value):print("__setitem__(key=", key, ',value=', value,')')self.data[key] = valuedef __delitem__(self, key):print('正在刪除第', key, '個元素')L1 = MyList([1, -2, 3, -4, 5])v = L1[2] # 調用 v = L1.__getitem__(2)print(v) # 3L1[1] = 2 # 調用 L1.__setitem__(1, 2)print(L1)del L1[3] # 調用 L1.__delitem__(3)
View Code
  class MyList:def __init__(self, iterable=()):self.data = [x for x in iterable]def __repr__(self):return "MyList(%s)" % self.datadef __getitem__(self, item):print("__getitem__:", item)if type(item) is int:print("正在做索引操作,item=", item)elif type(item) is slice:print("正在做切片操作:")print("起始值:", item.start)print("終止值:", item.stop)print("步長:", item.step)return self.data[item]L1 = MyList([1, -2, 3, -4, 5])v = L1[1::2]print(v)v = L1[3]print(v)# L1[1:2:3] = [4, 5, 6]# L1.__setitem__(slice(1, 2, 3), [4, 5, 6])
View Code

slice 構造函數
  作用:
    用于創建一個slice切片對象,此對象存儲一個切片的起始值,終止值,步長信息
  格式:
    slice(start=None, stop=None, step=None)
  slice對象的實例屬性
    s.start 切片的起始值,默認為None
    s.stop 切片的終止值,默認為None
    s.step 切片的步長,默認為None

?

特性屬性 @property
  實現其它語言所擁有的getter 和 setter功能
作用:
  用來模擬一個屬性
  通過@property裝飾器可以對模擬屬性賦值和取值加以控制

  class Student:def __init__(self, s):self.__score = s # 成績
@propertydef score(self):'''getter'''return self.__score@score.setterdef score(self, new_score):'''setter'''assert 0 <= new_score <= 100, '成績不合法'self.__score = new_scores1 = Student(50)print(s1.score)s1.score = 999 # 用setter來控制賦值操作print(s1.score)
View Code

?

轉載于:https://www.cnblogs.com/zhaoyang1997/p/10747211.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387814.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387814.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387814.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

反射賦值

目前例子為NPOI Excel導入 入庫時調用 var file file1.PostedFile.InputStream;var fileExt System.IO.Path.GetExtension(file1.FileName);IWorkbook workbook;if (fileExt ".xlsx")workbook new XSSFWorkbook(file);elseworkbook new HSSFWorkbook(file);DB.D…

基于PCA(主成分分析)的人臉識別

代碼下載&#xff1a;基于PCA&#xff08;主成分分析&#xff09;的人臉識別 人臉識別是一個有監督學習過程&#xff0c;首先利用訓練集構造一個人臉模型&#xff0c;然后將測試集與訓練集進行匹配&#xff0c;找到與之對應的訓練集頭像。最容易的方式是直接利用歐式距離計算測…

從BMW Vision iNEXT 看寶馬如何進軍自動駕駛

安全很重要&#xff0c;空間也要很大&#xff0c;砍掉大量物理按鍵&#xff0c;內飾材料要環保&#xff0c;還要提供自動和主動兩套駕駛方案。這些描述僅是BMW Vision iNEXT&#xff08;下稱Vision iNEXT&#xff09;概念車的設計之冰山一角。 一款概念車當然無法完全代表未來…

CSS浮動(二)---Float

重新認識float 2.1. 誤解和“誤用” 既然提到“誤用”&#xff0c;各位看官就此想想&#xff0c;自己平日是怎么使用float的&#xff1f;另外&#xff0c;既然“誤用”加了引號&#xff0c;就說明這樣的使用并不是真正的誤用&#xff0c;而是誤打誤撞使用之后&#xff0c;帶…

Hadoop0.20.2版本在Ubuntu下安裝和配置

1、安裝JDK   &#xff08;1&#xff09;下載安裝JDK&#xff1a;確保計算機聯網之后命令行輸入下面命令安裝JDK   sudo apt-get install sun-java6-jdk   &#xff08;2&#xff09;配置計算機Java環境&#xff1a;打開/etc/profile&#xff0c;在文件最后輸入下面內容 …

云原生生態周報 Vol. 2

業界要聞 Kubernetes External Secrets 近日&#xff0c;世界上最大的域名托管公司 Godaddy公司&#xff0c;正式宣布并詳細解讀了其開源的K8s外部 Secrets 管理項目&#xff1a; Kubernetes External Secrets&#xff0c;簡稱KES。這個項目定義了ExternalSecrets API&#xff…

centos 7新機使用前操作

關閉防火墻 systemctl stop firewalld&#xff08;停服務&#xff09; systemctl status firewalld&#xff08;看狀態&#xff09; systemctl disable firewalld.service &#xff08;永久關閉&#xff09; selinux getenforce&#xff08;查狀態&#xff09; vi /etc/selinux…

ubuntu10.04+hadoop0.20.2平臺配置(完全分布式模式)

配置環境及有關工具&#xff1a;ubuntu10.04 、hadoop0.20.2 、 jdk1.6.0_29 我們的機器有三臺&#xff0c;一臺當作namenode、兩臺當作datanode&#xff1a; namenode&#xff1a;IP:192.168.0.25、機器名&#xff1a;kiddenzj &#xff08;這里的機器名要注意&#xff1a;機…

成佛、遠不止渡滄海

地之及東南&#xff0c;有一海&#xff0c;稱為“滄海”。滄海對面&#xff0c;就是仙家佛地。凡是能渡過滄海到達彼岸的人&#xff0c;就能立地成佛&#xff0c;修成正果。 于是&#xff0c;許許多多的人千里迢迢趕來&#xff0c;或乘帆船&#xff0c;或乘木筏&#xff0c;紛紛…

軟件架構演進

傳統架構到分布式架構詳解 軟件架構演進軟件架構的發展經歷了從單體架構、垂直架構、SOA架構到微服務架構的過程&#xff0c;博客里寫到了這四種架構的特點以及優缺點分析&#xff0c;個人學習之用&#xff0c;僅供參考&#xff01; 1.1.1 單體架構 特點&#xff1a;1、所有的…

hadoop0.20.0第一個例子

這是Hadoop學習全程記錄第2篇&#xff0c;在這篇里我將介紹一下如何在Eclipse下寫第一個MapReduce程序。 新說明一下我的開發環境&#xff1a; 操作系統&#xff1a;在windows下使用wubi安裝了ubuntu 10.10 hadoop版本&#xff1a;hadoop-0.20.2.tar.gz Eclipse版本&…

IDEA 修改JavaWeb的訪問路徑

問題描述 對于我這個剛剛使用IDEA不久的新手來說&#xff0c;能夠正常運行就不錯了,不過到了后面&#xff0c;可能會覺得IDEA給你分配的默認訪問路徑很不順手&#xff0c;比如訪問的時候需要通過: http://localhost:8080/web_war_exploded/ 來訪問&#xff0c;對于web_w…

防撞庫基本要求

專用安全要求 口令要求 設計要求說明 要求 是否滿足 密碼長度至少 8位字符&#xff0c;密碼復雜性要求至少包含以下4種類別中的2種&#xff1a;大寫字母、小寫字母、數字、特殊符號 必選 滿足 系統應具備對口令強度檢測的能力&#xff0c;并對用戶進行提示&#xff08;盡量不要…

odoo10 繼承(擴展)、模塊數據

一&#xff1a;繼承 在不改變底層對象的時候添加新的功能——這是通過繼承機制來實現的&#xff0c;作為在現有對象之上的修改層&#xff0c;這些修改可以發生在所有級別&#xff1a;模型&#xff0c;視圖和業務邏輯。不是直接修改現有模塊&#xff0c;而是創建一個新模塊以添加…

做一個vue的todolist列表

<template><div id"app"><input type"text" v-model"todo" ref"ip"/><button click"add()">新增</button><br/><br/><hr/><ul><li v-for"(item,key) in li…

hadoop+hive-0.10.0完全分布式安裝方法

hadoophive-0.10.0完全分布式安裝方法 1、jdk版本&#xff1a;jdk-7u60-linux-x64.tar.gz http://www.oracle.com/technetwork/cn/java/javase/downloads/jdk7-downloads-1880260.html 2、hive版本&#xff1a;hive-0.10.0.tar.gz https://archive.apache.org/dist/hive/hive-0…

關于gitgithub的操作

先馬克&#xff0c;回頭細看&#xff0c;然后整理一下 https://linux.cn/article-4292-1.html轉載于:https://www.cnblogs.com/mengjie1001/p/10076530.html

一種解決 MacBook 里的 App Store 無法登錄的問題

剛剛買回來的 2018 款帶有 touchbar 的 MacBook Pro 15 inc 在用 App Store 安裝 app 時一直無法登錄成功&#xff08;網絡鏈接都是好的&#xff09;&#xff0c;導致軟件都無法更新&#xff0c;折騰了挺一會的。 后來發現是要退出設置里的 iCloud 登錄&#xff0c;然后重新登錄…

第二次沖刺

1、今日各個成員的問題 組員問題張晉誌對mui的API看得不是很懂&#xff0c;無法順利的使用袁慶杰基礎不牢,編寫困難周建峰eclipse沒法創建web項目&#xff0c;按照網上的方法&#xff0c;check for updates 和 install new software 之后也沒用許家燁給單一功能知道如何實現但項…

牌類游戲使用微服務重構筆記(八): 游戲網關服務器

網關服務器 所謂網關&#xff0c;其實就是維持玩家客戶端的連接&#xff0c;將玩家發的游戲請求轉發到具體后端服務的服務器&#xff0c;具有以下幾個功能點&#xff1a; 長期運行&#xff0c;必須具有較高的穩定性和性能對外開放&#xff0c;即客戶端需要知道網關的IP和端口&a…