1. 程式人生 > >2018.12.20 今日所學

2018.12.20 今日所學

今日所學 :

 1. isinstance , type , issubclass

 2.如何區分方法和函式(程式碼)

 3.反射(重要)

1. isinstance ,type ,issubclass

  isinstance(椅子音死ten死): 判斷你給的物件是否是xx型別的.(向上判斷)

 #應用
 def cul(a,b):  #次函式用來計算數字a和數字b的相加的結果
        判斷傳遞進來的物件必須是數字.int(整數) float (小數)
    if (type(a)==int or type(a)==float) and (type(b)==int or type(b)==float):
        return a+b
    else:
        print('對不起,你提供的資料無法進行計算')
print(cul(a,c)) 

 

  type : 精準的判斷返回xxx物件的資料型別

class Animal:
    def eat(self):
        print("剛睡醒吃點兒東西")

class Cat(Animal):
    def play(self):
        print("貓喜歡玩兒")

c = Cat()
a=animal()
    print(isinstance(a,cat)) #不能向下判斷

print(type(a)) # 返回 a的資料型別
print(type([]))
print(type(c)) # 精準的告訴你這個物件的資料型別

 

  

 

  issubclass: 判斷xxx是否是xxx的子類

print(issubclass(Cat, Animal))
print(issubclass(Animal, Cat))

 

2.如何區分方法和函式(程式碼)

在類中 :

 例項方法: 如果是類名.方法 這時是函式

      如果是物件.方法 這時是方法

靜態方法: 類名.方法 和物件.方法都是函式

類方法: 類名.方法 和物件.方法都是方法

這裡要引入一個模組 

form  types import MethodType,FunctionType 

3 .反射 (重要)

反射主要涉及到了4個函式 

getattr(a,b) 從a中獲取到b資料

setattr(a,b,c) 將a中的b更改為c(設定a中的b屬性為c)

hasattr(a,b) 判斷a中是否存在b資料

delattr(a,b) 刪除a中b的資料(不是將原資料變成None)