1. 程式人生 > >python isinstance和issubclass,區分方法和函式,反射

python isinstance和issubclass,區分方法和函式,反射

一.isinstance和issubclass

1.isinstance

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


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

c = Cat()

print(isinstance(c, Cat))  # c是一隻貓
print(isinstance(c, Animal))  # 向上判斷 c是一隻動物

2.issubclass

 1 class Animal:
 2     def
eat(self): 3 print('剛睡醒吃點兒東西') 4 5 6 class Cat(Animal): 7 def play(self): 8 print('貓喜歡玩兒') 9 10 c = Cat() 11 print(issubclass(Cat, Animal)) # 判斷Cat類是否是Animal類的子類 12 print(issubclass(Animal, Cat)) # 判斷Animal類是否是Cat類的子類

二.區分方法和函式

官方玩法

 1 from types import FunctionType,MethodType  #
方法和函式 FunctionType 函式型別 MethodType 方法型別 2 from collections import Iterable, Iterator # 迭代器 3 4 5 class Person: 6 def chi(self): # 例項方法 7 print('我要吃魚') 8 9 @classmethod 10 def he(cls): 11 print('我是類方法') 12 13 @staticmethod 14 def pi(): 15 print
('你是真的皮') 16 17 p =Person() 18 19 print(isinstance(Person.chi, FunctionType)) # True 20 print(isinstance(p.chi, MethodType)) # True 21 22 print(isinstance(p.he, MethodType)) # True 23 print(isinstance(Person.he, MethodType)) # True 24 25 print(isinstance(p.pi, FunctionType)) # True 26 print(isinstance(Person.pi, FunctionType)) # True

野路子

列印的結果中包含了function. 函式
method. 方法
 1 def func():
 2     print('我是函式')
 3 
 4 class Foo:
 5     def chi(self):
 6         print('我是吃')
 7 
 8 print(func)  #<function func at 0x0000024817BF1E18>
 9 f = Foo()
10 f.chi()
11 print(f.chi)  # <bound method Foo.chi of <__main__.Foo object at 0x0000024817DCC358>>

 

三.反射

 1 class Preson:
 2     def __init__(self, name, laopo):
 3         self.name = name
 4         self.laopo = laopo
 5 
 6 
 7 p = Preson('寶寶', '林志玲')
 8 
 9 print(hasattr(p, 'laopo'))  # p這個物件中是否有老婆這個屬性
10 print(getattr(p, 'laopo'))  # p.laopo 獲取p這個物件中的老婆屬性
11 
12 # 設定一個物件屬性若存在就修改 不存在就新增到這個物件中
13 setattr(p, 'laopo', '胡一菲')  # p.laopo = 胡一菲
14 setattr(p, 'money', 10000000)  # p.money = 10000000
15 
16 print(p.laopo)
17 print(p.money)
18 
19 # delattr(p, 'laopo')  # 把物件中的xxx屬性移除   != p.laopo = None
20 print(p.laopo)  #'Preson' object has no attribute 'laopo' 已經移除了物件中的laopo屬性所以報錯