類、面向對象(封裝、繼承、多態),面向過程

類:
	屬性:
		實例變量
		類變量
		私有屬性__var
	方法:
		構造方法
		析構函數
		私有方法
對象:一個類實例化之後的得到的對象
封裝:把一些功能的實現細節不對外暴露
繼承:
	代碼的重用
	單繼承
	多繼承
		2.x、經典類,深度優先				新式類,廣度優先
		3.x、都是廣度優先
		繼承的時候:

		class Foo(SchoolMember):
		    def __init__(self,name,age,sex,selary,coures):		#括號裏寫全參數,先寫父類的,再寫自己的
    			super(Foo,self).__init__(name,age,sex)			#前面寫子類的名字,後面寫父類的參數
    			#SchoolMember.__init__(self,name,age,sex)		#經典類的寫法,上面是新式類的寫法
    			self.selary = selary
    			self.course = coures
多態:接口的重用        		
靜態方法:只是名義上歸類管理,實際上在靜態方法裏訪問不了類或實例中的任何屬性
類方法:只能訪問類變量,不能訪問實例變量
屬性方法:把一個方法變成一個靜態屬性
反射:
	hasattr(obj,name_str),判斷一個對象裏是否有對應的字符串的方法
	getattr(object, name, default=None),根據字符串去獲取obj對象裏的對應的方法的內存地址
	setattr(x, y, v)
異常處理    	
動態導入模塊
斷言
面向過程 VS 面向對象
編程範式:
    編程是程序員用特定語法+數據結構+算法組成的代碼來告訴計算機如何執行任務的過程,一個程序是程序員爲了得到一個任務結果而
編寫的一組指令的集合,正所謂條條大路通羅馬,實現一個任務的方式有很多種不同的方式,對這些不同的編程方式的特點進行歸納總結
得出來的編程方式類別,即爲編程範式。不同的編程範式本質上代表對各種類型的任務採取的不同的解決問題的思路,大多數語言只支持
一種編程範式,當然也有些語言可以同時支持多種編程範式。
    兩種最重要的編程範式分別是面向過程編程和麪向對象編程。
面向過程編程(Procedural Programming):
   Procedural programming uses a list of instructions to tell the computer what to do step-by-step. 
面向過程編程依賴-你猜到了-procedures,一個procedure包含一組要被進行計算的步驟,面向過程又被稱爲top-down languages,
就是程序從上到下一步步執行,一步步從上到下,從頭到尾的解決問題 。基本設計思路就是程序一開始是要着手解決一個大的問題,
然後把一個大問題分解成很多個小問題或子過程,這些子過程再執行的過程再繼續分解直到小問題足夠簡單到可以在一個小步驟範圍內解決。

1、面向對象介紹:

   Object-Oriented Programming
OOP編程是利用“類”和“對象”來創建各種模型來實現對真實世界的描述,使用面向對象編程的原因一方面是因爲它可以使程序的維護和
擴展變得更簡單,並且可以大大提高程序開發效率,另外,基於面向對象的程序可以使它人更加容易理解你的代碼邏輯,從而使團隊開發
變得更從容。
   面向對象的幾個核心特性如下:
1.1、Class 類:

一個類即是對一類擁有相同屬性的對象的抽象、藍圖、原型。在類中定義了這些對象的都具備的屬性(variables(data))、共同的方法

1.2、Object 對象 :

一個對象即是一個類的實例化後實例,一個類必須經過實例化後方可在程序中調用,一個類可以實例化多個對象,每個對象亦可以有不同的屬性,
就像人類是指所有人,每個人是指具體的對象,人與人之前有共性,亦有不同

1.3、Encapsulation 封裝:

不對外暴露細節,只提供一個接口
在類中對數據的賦值、內部調用對外部用戶是透明的,這使類變成了一個膠囊或容器,裏面包含着類的數據和方法

1.4、Inheritance 繼承:

一個類可以派生出子類, 在這個父類裏定義的屬性、方法自動被子類繼承

1.5、Polymorphism 多態:

多態是面向對象的重要特性,簡單點說:“一個接口,多種實現”,指一個基類中派生出了不同的子類,且每個子類在繼承了同樣的方法名的同時又對父類的方法做了不同的實現,這就是同一種事物表現出的多種形態。
編程其實就是一個將具體世界進行抽象化的過程,多態就是抽象化的一種體現,把一系列具體事物的共同點抽象出來, 再通過這個抽象的事物, 與不同的具體事物進行對話。
對不同類的對象發出相同的消息將會有不同的行爲。比如,你的老闆讓所有員工在九點鐘開始工作, 他只要在九點鐘的時候說:“開始工作”即可,而不需要對銷售人員說:“開始銷售工作”,對技術人員說:“開始技術工作”, 因爲“員工”是一個抽象的事物, 只要是員工就可以開始工作,他知道這一點就行了。至於每個員工,當然會各司其職,做各自的工作。
多態允許將子類的對象當作父類的對象使用,某父類型的引用指向其子類型的對象,調用的方法是該子類型的方法。這裏引用和調用方法的代碼編譯前就已經決定了,而引用所指向的對象可以在運行期間動態綁定.

1.6、例子:
class Role(object):
	n = 123									#類變量
    def __init__(self,name,role,weapon,life_value=100,money=15000):		
    #構造函數
    #在實例化時,做一些類的初始化的工作
        self.name = name					#實例變量(靜態屬性),作用域是實例本身
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.money = money
 
    def shot(self):							#類的方法,類的功能(動態屬性)
        print("shooting...")
 
    def got_shot(self):
        print("ah...,I got shot...")
 
    def buy_gun(self,gun_name):
        print("just bought %s" %gun_name)

print(Role.n) 
r1 = Role('Alex','police','AK47)    		#實例化(把一個類變成具體對象的過程)
print(r1.n,r1.name)
r1.name = "李尚"								#可以修改實例中的值
print(r1.n,r1.name)
r2 = Role('Jack','terrorist','B22)  		#生成一個角色r2,,,r1和r2叫Role這個類的實例
print(r2.n,r2.name)
r1.buy_gun("M16")
r1.got_shot							 		#殺死r1   ===   相當於Role.got_shot(r1)
r1.bullet_prove = True						#也可以在實例化之後再添加屬性
print(r1.n,r1.name,r1.bullet_prove)
del r1.weapon								#刪除一條屬性
r1.n = "改類變量"							#直接在r1的內存裏生成了新的 n = "改類變量"
print("r1:",r1.name,r1.n)
print("r2:",r2.name,r2.n)

--->
123
123 Alex
123 李尚
123 Jack
Alex just bought M16
ah...,I got shot...

r1: 李尚 改類變量								#只是在r1的內存裏生成了一個新的 n = "改類變量"
r2: Jack 123								#r2裏沒有n,就去調用類裏的 n = 123

2、類變量的用途?大家共用的屬性,節省開銷

3、構造函數:

def __init__(self,n1,n2,n3):
	self.n1 = n1
	self.n2 = n2
	self.n3 = n3

4、析構函數:在實例釋放、銷燬的時候執行的,通常用於做一些收尾工作,如關閉一些數據庫連接、關閉一些打開的臨時文件

#用法1:__del__()析構函數會在程序執行完時自執行
class Role:
    def __init__(self, name, role, weapon, life_value=100, money=15000):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.money = money

    def __del__(self):
        print("%s 徹底死了..."% self.name)

    def shot(self):
        print("shooting...")
    def got_shot(self):
        print("ah...,I got shot...")
    def buy_gun(self, gun_name):
        print("%s just bought %s" % (self.name,gun_name))

r1 = Role('Alex', 'police', 'AK47')
r1.buy_gun("M4A1")
r1.got_shot()
r2 = Role('Jack', 'terrorist', 'B22')
r2.got_shot()

--->
Alex just bought M4A1
ah...,I got shot...
ah...,I got shot...
Alex 徹底死了...						#程序執行完畢時自動執行__del()__
Jack 徹底死了...						#同上

也可以在程序執行過程中手動執行__del()__

#用法2:在程序執行過程中手動執行析構函數
class Role:
    def __init__(self, name, role, weapon, life_value=100, money=15000):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.money = money

    def __del__(self):
        print("%s 徹底死了..."% self.name)

    def shot(self):
        print("shooting...")
    def got_shot(self):
        print("ah...,I got shot...")
    def buy_gun(self, gun_name):
        print("%s just bought %s" % (self.name,gun_name))

r1 = Role('Alex', 'police', 'AK47')
r1.buy_gun("M4A1")
r1.got_shot()
del r1											#手動執行r1的死亡
r2 = Role('Jack', 'terrorist', 'B22')
r2.got_shot()

--->
Alex just bought M4A1
ah...,I got shot...
Alex 徹底死了...									#這時Alex的死亡就會出現在r2的實例之前,而不是等程序執行完畢再執行
ah...,I got shot...
Jack 徹底死了...

5、私有方法,私有屬性(變量)

##私有屬性和私有方法
class Role:
    def __init__(self, name, role, weapon, life_value=100, money=15000):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.__life_value = life_value				#前面加__,變爲私有屬性,對外不可見,在內部可以添加一個方法
        self.money = money

    def __shot(self):								#前年加__,變爲私有方法,外面不能直接調用這個方法
        print("shooting...")
    def got_shot(self):
        print("ah...,I got shot...")
    def buy_gun(self, gun_name):
        print("%s just bought %s" % (self.name,gun_name))
	def show_status(self):
        print("name:%s weapon:%s life_val:%s" %(self.name,self.weapon,self.__life_value))
r1 = Role('Alex', 'police', 'AK47')
print(r1.show_status)

--->
name:Alex weapon:AK47 life_val:100

6、類的繼承:

#經典類
class People():
    def __init__(self,name,age,):
        self.name = name
        self.age = age

    def eat(self):
            print("%s is eating..." % self.name)
    def talk(self):
            print("%s is talking..." % self.name)
    def sleep(self):
            print("%s is sleepping..." % self.name)

class Man(People):									
    def __init__(self,name,age,money):				#想讓Man調用繼承的父類People()時有單獨的屬性,再重新def一次
        People.__init__(self,name,age)				#把父類的方法都調用過來
        
        ################################################################################
        #super(Man,self).__init__(name.age)					#方法2:與上一行效果完全一樣()  #新式類的寫法
        ################################################################################
        
        self.money = money							#這個是自己新加的
        print("%s 一出生就有%s money"%(self.name,self.money))

	def piao(self):
        print("%s is piaoing ..... 20s....done" % self.name)

    def sleep(self):							#父類本身有sleep方法,在此處重構父類的方法
        People.sleep(self)						#調用的父類的方法
        print("man is sleepping")				#自己添加的新功能

class Woman(People):
    def get_birth(self):
        print("%s is born a baby" % self.name)   

m1 = Man('lishang',23,'10000000000')			#調用Man()就得需要3個參數
m1.eat()										#eat是從父親People()繼承的方法
m1.piao()										#piao是Man()自己的方法
m1.sleep()
w1=Woman("Houruijuan",26)						#調用Woman()只需從父類繼承的2個參數
w1.get_birth()

--->
lishang 一出生就有10000000000 money
lishang is eating...
lishang is piaoing ..... 20s....done
lishang is sleepping...
man is sleepping
Houruijuan is born a baby
6.1、新式類與經典類區別主要在多繼承上:
#新式類
class People(object):
    def __init__(self,name,age,):
        self.name = name
        self.age = age

    def eat(self):
        print("%s is eating..." % self.name)
    def talk(self):
        print("%s is talking..." % self.name)
    def sleep(self):
        print("%s is sleepping..." % self.name)

class Relation(object):
    #def __init__(self):
    def make_friends(self,obj):
        print("%s is making friends with %s" %(self.name,obj.name))

class Man(People,Relation):
    def __init__(self,name,age,money):
        super(Man,self).__init__(name,age)
        self.money = money
        print("%s 一出生就有%s money"%(self.name,self.money))

    def piao(self):
        print("%s is piaoing ..... 20s....done" % self.name)
    def sleep(self):
        People.sleep(self)
        print("man is sleepping")

class Woman(People,Relation):
    def get_birth(self):
        print("%s is born a baby" % self.name)

m1=Man('lishang',23,'10000000000')
w1=Woman("ZhaoXiaomeng",26)

m1.make_friends(w1)

--->
lishang 一出生就有10000000000 money
lishang is making friends with ZhaoXiaomeng
6.2、多繼承的廣度優先原則
先找與他相連接的最近的類,找完該層級後,再去找他們的父類
class A:
    def __init__(self):
        print("A")
class B(A):
    pass
    # def __init__(self):
    #     print("B")
class C(A):
    def __init__(self):
        print("C")
class D(B,C):
    pass
    # def __init__(self):
    #     print("D")

D()

--->
C									#執行D的時候,會先找B,再找同級的C,最後才找上層的A(廣度優先原則)
6.3、深度優先原則
深度優先查詢方法:先找B,再找B的父類,然後才找與B同層的C類
6.4、python2 和 python3上經典類與新式類繼承方式的區別
在python2上,經典類是按深度優先來繼承的,新式類先按廣度優先來繼承的
在python3上,經典類和新式類都是統一按廣度優先來繼承的

python2上,將第一行 class A: 改爲 class A(object): 就將經典類變成了新式類,再次查詢就按照廣度優先的方法查找了

7、類—多態,“一個接口,多種實現”

   多態性(polymorphish)是允許你將父對象設置成和一個更多的他的子對象相等的技術,賦值之後,父對象就可以根據當前賦值給它的
子對象的特性以不同的方式運作。簡單的說,一句話:允許將子類類型的指針賦值給父類類型的指針。
   多態的作用是什麼呢?我們知道,封裝可以隱藏顯示細節,使得代碼模塊化;繼承可以擴展已存在的代碼模塊(類)。他們的目的都是
爲了--代碼重用。那麼多態則是爲了實現另一個目的--接口重用!多態的作用就是爲了類在繼承和派生的時候,保證使用"家譜"中任一
類的實例的某一屬性時的正確調用。
  • python不直接支持多態,但可以間接實現
class Animal(object):
    def __init__(self,name):
        self.name = name

    def talk(self):
        pass

    @staticmethod										#裝飾器,一個靜態方法,跟類沒關係
    def animal_talk(obj):
        obj.talk()

class Dog(Animal):
    def talk(self):
        print('%s: 汪!汪!汪!'%self.name)

class Cat(Animal):
    def talk(self):
        print('%s: Meow~ Meow~' % self.name)

a = Dog('趙曉萌')
b = Cat('孫凱欣')
Animal.animal_talk(a)									#同一個接口,不同的表現形式
Animal.animal_talk(b)

--->
趙曉萌: 汪!汪!汪!
孫凱欣: Meow~ Meow~

8、靜態方法

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

    @staticmethod							#加上這個裝飾器,這個功能和類已經沒有關係,d.eat()不能直接調用
    def eat(self):
        print("%s is eatting %s" % (self.name,'包子'))

d = Dog('趙曉萌')
d.eat(d)									#因爲和上面的eat加上了這個裝飾器,想再調用得把d傳進來

--->
趙曉萌 is eatting 包子

9、類方法

class Dog(object):
    name = 'lishang'

    def __init__(self,name):
        self.name = name

    @classmethod
    def eat(self):
        print("%s is eatting %s" % (self.name,'包子'))

d = Dog('趙曉萌')
d.eat()

--->
lishang is eatting 包子									#明明傳得是'趙曉萌',得到的卻是lishang

10、屬性方法

class Dog(object):
    name = 'lishang'

    def __init__(self,name):
        self.name = name

    @property									#將方法轉爲了一個屬性
    def eat(self):
        print("%s is eatting %s" % (self.name,'包子'))

    @eat.setter									#修改這個屬性
    def eat(self,food):
        print("set to food:",food)
        self.__food = food

    @eat.deleter								#刪除這個屬性
    def eat(self):
        del self.__food
        print("刪完了")
        
d = Dog('趙曉萌')
d.eat
d.eat = '包子'
d.eat
del d.eat

--->
趙曉萌 is eatting 包子
set to food: 包子
趙曉萌 is eatting 包子
刪完了

11、一些特殊方法

  1. doc  表示類的描述信息
class Dog(object):
    '''這個類是描述狗這個對象的'''
    def __init__(self,name):
        self.name = name
        self.__food = None

    @property
    def eat(self):
        print("%s is eatting %s" % (self.name,self.__food))
    @eat.setter
    def eat(self,food):
        print("set to food:",food)
        self.__food = food
    @eat.deleter
    def eat(self):
        del self.__food
        print("刪完了")

print('1:',Dog.__doc__)					#打印這個類的描述信息

--->
1:這個類是描述狗這個對象的

2、moduleclass

##/lib/aa
class C(object):
    def __init__(self):
        self.name = 'lishang'
##index.py
from lib.aa import C

obj = C()
print (obj.__module__)        # 輸出 lib.aa,即:輸出C是從哪個模塊導出來的
print (obj.__class__)         # 輸出 lib.aa.C,即:輸出類

--->
lib.aa
<class 'lib.aa.C'>
  1. call 對象後面加括號,觸發執行
class Foo:
 
    def __init__(self):
        pass
     
    def __call__(self, *args, **kwargs):
 
        print '__call__'
 
 
obj = Foo() # 執行 __init__
obj()       # 執行 __call__
  1. dict 查看類或對象中的所有成員
class Dog(object):
    #name = 'lishang'
    '''這個類是描述狗這個對象的'''
    def __init__(self,name):
        self.name = name
        self.__food = None

    def eat(self):
        print("%s is eatting %s" % (self.name,self.__food))

print('6:',Dog.__dict__)				#打印類裏的所有屬性,不包括實例屬性
d = Dog('趙曉萌')
print('6:',d.__dict__)					#打印所有實例屬性,不包括類屬性

--->
6: {'__module__': '__main__', '__doc__': '這個類是描述狗這個對象的', '__init__': <function Dog.__init__ at 0x00000000027C43A8>, 'eat': <property object at 0x00000000027068B8>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>}
6: {'name': '趙曉萌', '_Dog__food': None}

7.str 如果一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。

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

    def __str__(self):
        return '<obj:%s>' %self.name

obj = Foo('lishang')
print (obj)

--->
<obj:lishang>								#返回了__str__(self)方法的返回值

8.getitemsetitemdelitem
用於索引操作,如字典。以上分別表示獲取、設置、刪除數據

class Foo(object):
 
    def __getitem__(self, key):
        print('__getitem__',key)
 
    def __setitem__(self, key, value):
        print('__setitem__',key,value)
 
    def __delitem__(self, key):
        print('__delitem__',key)
 
obj = Foo()
 
result = obj['k1']      # 自動觸發執行 __getitem__
obj['k2'] = 'alex'   	# 自動觸發執行 __setitem__
del obj['k1']   
  1. new \ metaclass
###a). 普通方式 
class Foo(object):
  
    def func(self):
        print ('hello alex')
        
###b). 特殊方式
def func(self):
    print 'hello wupeiqi'
  
Foo = type('Foo',(object,), {'func': func})
#type第一個參數:類名
#type第二個參數:當前類的基類
#type第三個參數:類的成員

###c). 手動將函數鏈接成類
def func(self):
    print( 'hello %s' % self.name)

def __init__(self,name,age):
    self.name = name
    self.age = age

Foo = type('Foo', (object,), {'talk': func,
                              '__init__':__init__})

f = Foo('lishang','22')
f.talk()
print(type(Foo))

--->
hello lishang
<class 'type'>

12、學校的例子,類的繼承、組合等

class School(object):
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr
        self.students = []
        self.teachers = []
        self.staffs = []

    def enroll(self,stu_obj):
        print("爲%s學生辦理註冊手續" % stu_obj.name)
        self.students.append(stu_obj)

    def hire(self,staff_obj):
        print("僱傭新員工%s" % staff_obj.name)
        self.staffs.append(staff_obj)

class SchoolMember(object):
    def __init__(self,name,age,sex,):
        self.name = name
        self.age = age
        self.sex = sex

    def tell(self):
        pass

class Teacher(SchoolMember):
    def __init__(self,name,age,sex,selary,coures):
        super(Teacher,self).__init__(name,age,sex)
        self.selary = selary
        self.course = coures

    def tell(self):
        print('''
        ------ info of Teacher:%s
        Name:%s
        Age:%s
        Sex:%s
        Selary:%s
        Coures:%s
        '''%(self.name,self.name,self.age,self.sex,self.selary,self.course))

    def teach(self):
        print("%s is teaching course [%s]" % (self.name,self.course))

class Student(SchoolMember):
    def __init__(self,name,age,sex,stu_id,grade):
        super(Student,self).__init__(name,age,sex)
        self.stu_id = stu_id
        self.grade = grade

    def tell(self):
        print('''
        ------ info of Student:%s
        Name:%s
        Age:%s
        Sex:%s
        Stu_id:%s
        Grade:%s
        '''%(self.name,self.name,self.age,self.sex,self.stu_id,self.grade))

    def pay_tuition(self,account):
        print("%s has paid tuition for $%s" %(self.name,account) )

school = School('老男孩IT','沙河')
t1 = Teacher('oldboy',56,'mf',2000000,'linux')
t2 = Teacher('alex',22,'boy',3000,'python')
s1 = Student('李尚',23,'boy',20110001,'gao1')
s2 = Student('趙曉萌',22,'girl',20110002,'gao2')

s1.tell()
t1.tell()
school.enroll(s1)
school.enroll(s2)

school.hire(t1)
school.staffs[0].teach()

for stu in school.students:
    stu.pay_tuition(5000)

--->###運行結果:

        ------ info of Student:李尚
        Name:李尚
        Age:23
        Sex:boy
        Stu_id:20110001
        Grade:gao1
        

        ------ info of Teacher:oldboy
        Name:oldboy
        Age:56
        Sex:mf
        Selary:2000000
        Coures:linux
        
爲李尚學生辦理註冊手續
爲趙曉萌學生辦理註冊手續
僱傭新員工oldboy
oldboy is teaching course [linux]
李尚 has paid tuition for $5000
趙曉萌 has paid tuition for $5000

13、反射

通過字符串映射或修改程序運行時的狀態、屬性、方法, 有以下4個方法
getattr(object, name, default=None)		#根據字符串去獲取obl對象裏的對應的方法的內存地址
hasattr(object,name)					#判斷一個對象obj裏是否有對應的name_str字符串的方法
setattr(x, y, v)						#相當於` x.y = z `,
delattr(x, y)							#刪除一段屬性
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 eatting" %self.name,food)

d = Dog("Zhao Xiao Meng")
choice = input(">>>:").strip()
print(hasattr(d,choice))

if hasattr(d,choice):
    func = getattr(d,choice)            #d.eat('椰子')
    func("椰子")
    delattr(d,choice)
else:
    setattr(d,choice,bulk)
    d.talk(d)

--->
>>>:eat
Zhao Xiao Meng is eatting 椰子
>>>:talk
22

14、異常處理

list = [1,2,3]
data = {}

try:
    list[3]
    data['name']
except KeyError as e:
    print("沒有這個key:",e)
except IndexError as e:
    print("列表操作錯誤:",e)

except Exception as e:				#這個是總的方法,可以卸寫在最後
    print("未知出錯了:",e)
else:								#前面的錯誤提示沒有捕捉到,就爲正常
    print("一切正常")
finally:							#不管是否有錯誤,最後都執行這個
    print("不管有沒有錯誤都執行")   
--->

列表操作錯誤: list index out of range
不管有沒有錯誤都執行
  • 常見的異常錯誤類型
AttributeError 		試圖訪問一個對象沒有的樹形,比如foo.x,但是foo沒有屬性x
IOError 			輸入/輸出異常;基本上是無法打開文件
ImportError 		無法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError 	語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 			下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]
KeyError 			試圖訪問字典裏不存在的鍵
KeyboardInterrupt 	Ctrl+C被按下
NameError 			使用一個還未被賦予對象的變量
SyntaxError 		Python代碼非法,代碼不能編譯
TypeError 			傳入對象類型與要求的不符合
UnboundLocalError 	試圖訪問一個還未被設置的局部變量,基本上是由於另有一個同名的全局變量,導致你以爲正在訪問它
ValueError 			傳入一個調用者不期望的值,即使值的類型是正確的
14.1、自定義異常
class LiShangException(Exception):
    def __init__(self, msg):
        self.message = msg
    # def __str__(self):				#這一段可加可不加,基類(Exception)已定義好了
    #     return self.message

try:
    raise LiShangException('大橋未久的異常')
except LiShangException as e:
    print(e)

--->
大橋未久的異常
15、動態導入模塊
###第一種情況,python解釋器內部自己的用法
文件夾lib下有aa.py
###cat aa.py
class C(object):
    def __init__(self):
        self.name = 'lishang'

與lib同級目錄下有'動態導入模塊.py'
lib = __import__('lib.aa')

obj = lib.aa.C()
print(obj.name)

--->
lishang

----------------------------------------------------------------
###第二種情況,官方建議		import importlib;aa = importlib.import_module('lib.aa')
import importlib
aa = importlib.import_module('lib.aa')

print(aa.C().name)

--->
lishang
16、斷言
用於安檢當前完全正確,確認沒毛病,才進行後面的步驟,否則就會報錯
a = 'lishang'
print(type(a))

assert type(a) is str
print("你說得對")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章