国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

淺析Python中的getattr(),setattr(),delattr(),hasattr()

2019-11-25 16:44:05
字體:
來源:轉載
供稿:網友

getattr()函數是Python自省的核心函數,具體使用大體如下:

獲取對象引用getattr

Getattr用于返回一個對象屬性,或者方法

class A: def __init__(self): self.name = 'zhangjing'    #self.age=''def method(self): print"method print" Instance = A() print getattr(Instance , 'name, 'not find') #如果Instance 對象中有屬性name則打印self.name的值,否則打印'not find'print getattr(Instance , 'age', 'not find') #如果Instance 對象中有屬性age則打印self.age的值,否則打印'not find'print getattr(a, 'method', 'default') #如果有方法method,否則打印其地址,否則打印default print getattr(a, 'method', 'default')() #如果有方法method,運行函數并打印None否則打印default 

注:使用getattr可以輕松實現工廠模式。

例:一個模塊支持html、text、xml等格式的打印,根據傳入的formate參數的不同,調用不同的函數實現幾種格式的輸出

import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format) return output_function(data) setattr(object, name, value)This is the counterpart of getattr(). The argumentsare an object, a string and an arbitrary value. The string may name an existingattribute or a new attribute. The function assigns the value to the attribute,provided the object allows it. For example, setattr(x,'foobar', 123) is equivalent tox.foobar = 123.

這是相對應的getattr()。參數是一個對象,一個字符串和一個任意值。字符串可能會列出一個現有的屬性或一個新的屬性。這個函數將值賦給屬性的。該對象允許它提供。例如,setattr(x,“foobar”,123)相當于x.foobar = 123。

delattr(object, name)

This is a relative of setattr(). The arguments are
an object and a string. The string must be the name of one of the object's
attributes. The function deletes the named attribute, provided the object allows
it. For example, delattr(x, 'foobar') is
equivalent to del x.foobar.

與setattr()相關的一組函數。參數是由一個對象(記住python中一切皆是對象)和一個字符串組成的。string參數必須是對象屬性名之一。該函數刪除該obj的一個由string指定的屬性。delattr(x, 'foobar')=del x.foobar

•hasattr用于確定一個對象是否具有某個屬性。

語法:

hasattr(object, name) -> bool

判斷object中是否有name屬性,返回一個布爾值。

>>> li=["zhangjing","zhangwei"]>>> getattr(li,"pop")<built-in method pop of list object at 0x011DF6C0>>>> li.pop<built-in method pop of list object at 0x011DF6C0>>>> li.pop()'zhangwei'>>> getattr(li,"pop")()'zhangjing'>>>getattr(li, "append")("Moe") 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昌吉市| 团风县| 高州市| 华阴市| 文山县| 昆明市| 海南省| 陇川县| 贵德县| 林西县| 连江县| 南昌市| 仙游县| 绥德县| 贞丰县| 南宫市| 丘北县| 库尔勒市| 揭西县| 高淳县| 乐陵市| 称多县| 疏勒县| 瑞安市| 安阳县| 会理县| 定结县| 玉门市| 徐水县| 彩票| 洛隆县| 南安市| 葵青区| 日照市| 龙南县| 冀州市| 贡觉县| 尚志市| 万安县| 丹江口市| 平果县|