Python筆記【7】_反射getattr&hasattr&setattr&delattr

Lesson0402_GetatrrWebsite.pypython

#!/usr/bin/env/python
#-*-coding:utf-8-*-

#Author:LingChongShi   #查看源碼Ctrl+左鍵

def index():
    print('歡迎訪問XX網站')

def login():
    print('登陸成功')

def logout():
    print('退出登陸')

class People(object):
    country='China'
    def __init__(self):
        pass
    def people_info(self):
        print('People類中people_info函數')
Lesson0403_Getattr.py
#!/usr/bin/env/python
#-*-coding:utf-8-*-

#Author:LingChongShi   #查看源碼Ctrl+左鍵

'''
getattr():根據字符串的形式去某個模塊中查找X函數
hasattr():根據字符串的形式去某個模塊判斷X函數是否存在
setattr():根據字符串的形式去某個模塊設置X函數
delattr():根據字符串的形式去某個模塊刪除X函數
'''
import Lesson04_Package.Lesson0402_GetatrrWebsite
'''getattr(object,name,default):
一、object:對象(模塊)
二、name:屬性(函數/方法)
三、default:無對應屬性,返回的值,
四、有對應屬性,返回對象屬性值
'''
getder=getattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'index','-1')
print(getder)
getder()

obj=Lesson04_Package.Lesson0402_GetatrrWebsite.People()
getclass=getattr(obj,'people_info','-1')
getclass()

'''hasattr(object,name):
一、object:對象(模塊)
二、name:屬性(函數/方法)
三、若是對象有該屬性返回True,不然返回False
'''
has=hasattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'login')
print(has)

obj=Lesson04_Package.Lesson0402_GetatrrWebsite.People()
hasclass=hasattr(obj,'people_info')
print(hasclass)

'''setattr(object,name,value):
一、object:對象(模塊)
二、name:屬性(函數/方法)
三、value:屬性值
四、無返回值
'''
set=setattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'str','添加的字符串')
has1=hasattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'str')
print(has1)
get1=getattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'str')
print(get1)

obj=Lesson04_Package.Lesson0402_GetatrrWebsite.People()
setclass=setattr(obj,'exit','退出')
hascalss=hasattr(obj,'exit')
print(hasclass)

'''delattr(object,name):
一、object:對象(模塊)
二、name:屬性(函數/方法)
三、無返回值
'''
del1=delattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'logout')
has2=hasattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'logout')
print(has2)
# get2=getattr(Lesson04_Package.Lesson0402_GetatrrWebsite,'logout')
# print(get2)

obj=Lesson04_Package.Lesson0402_GetatrrWebsite.People
hasclass=hasattr(obj,'people_info')
print(hasclass)
delclass=delattr(obj,'people_info')
hasclass=hasattr(obj,'people_info')
print(hasclass)
相關文章
相關標籤/搜索