1. 程式人生 > >python 面向物件(四)反射

python 面向物件(四)反射

####################總結##########

1.

isinstance: 判斷xxx是否是xxx型別的(向上判斷) 
type: 返回xx物件的資料型別
issubclass: 判斷xxx類是否是xxx類的子類

isinstance: 判斷xxx是否是xxx型別的(向上判斷)

class Animal:
    pass
class Cat(Animal):
    pass
class BoSiCat(Cat):
    pass
print(issubclass(Cat, Animal)) # 判斷第一個引數是否是第二個引數的後代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True

##########結果

True
False
True

type: 返回xx物件的資料型別

def add(a, b):
    if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float):
        return a + b
    else:
        print("算不了")

print(add("胡漢三", 2.5))

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

class Animal:
    pass
class Cat(Animal):
    pass
class BoSiCat(Cat):
    pass
print(issubclass(Cat, Animal)) # 判斷第一個引數是否是第二個引數的後代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True

#結果
True
False
True

2.

區分函式和方法

#方法一

def
func(): print("我是函式") class Foo: def
chi(self): print("我是吃") # print(func) # <function func at 0x0000000001D42E18> f = Foo() # f.chi() print(f.chi) # <bound method Foo.chi of <__main__.Foo object at 0x0000000002894A90>> # 野路子: 列印的結果中包含了function. 函式 # method . 方法
#方法二
from collections import Iterable, Iterator # 迭代器
from
types import FunctionType, MethodType # 方法和函式 class Person: def chi(self): # 例項方法 print("我要吃魚") @classmethod def he(cls): print("我是類方法") @staticmethod def pi(): print("泥溪鎮地皮")
p
= Person() print(isinstance(Person.chi, FunctionType)) # True print(isinstance(p.chi, MethodType)) # True

 3.反射

1. hasattr(物件, str) 判斷物件中是否包含str屬性
2. getattr(物件, str) 從物件中獲取到str屬性的值
3. setattr(物件, str, value) 把物件中的str屬性設定為value
4. delattr(物件, str) 把str屬性從物件中刪除

class Person:
    def __init__(self,name,laopo):
        self.name=name
        self.laopo=laopo
p= Person('寶寶','林志玲')

print(hasattr(p,'laopo'))
print(getattr(p,'laopo'))
setattr(p,'laopo','胡一菲')
setattr(p,'money',1000)

print(p.laopo)
print(p.money)
delattr(p, "laopo") # 把物件中的xxx屬性移除.  != p.laopo = None
print(p.laopo)

########結果
True
林志玲
胡一菲
1000

Traceback (most recent call last):
File "D:/python_work_s18/day18關係/test.py", line 87, in <module>
print(p.laopo)
AttributeError: 'Person' object has no attribute 'laopo'

Process finished with exit code 1

例項二  

####單獨檔案master
def chi():
    print("大牛很能吃")

def he():
    print("大牛一次喝一桶")

def shui():
    print("大牛一次睡一年")

def play_1():
    print("大牛不玩兒壓縮了. 玩兒兒童節")

def sa():
    print("大牛很能撒謊")

def la():
    print("大牛喜歡拉二胡")
while 1:
    content = input("請輸入你要測試的功能:") # 使用者輸入的功能是一個字串

    # 判斷 xxx物件中是否包含了xxxxx
    if hasattr(master, content):
        xx = getattr(master, content)
        xx()
        print("有這個功能")
    else:
        print('沒有這個功能')