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

首頁 > 編程 > Python > 正文

詳解Python3 中hasattr()、getattr()、setattr()、delattr()函數及示例代碼

2020-02-22 23:41:20
字體:
來源:轉載
供稿:網友

hasattr()函數

hasattr()函數用于判斷是否包含對應的屬性

語法:

hasattr(object,name)

參數:

object--對象

name--字符串,屬性名

返回值:

如果對象有該屬性返回True,否則返回False

示例:

class People:  country='China'  def __init__(self,name):    self.name=name  def people_info(self):    print('%s is xxx' %(self.name))obj=People('aaa')print(hasattr(People,'country'))#返回值:Trueprint('country' in People.__dict__)#返回值:Trueprint(hasattr(obj,'people_info'))#返回值:Trueprint(People.__dict__)##{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10205d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}

getattr()函數

描述:

getattr()函數用于返回一個對象屬性值

語法:

getattr(object,name,default)

參數:

object--對象

name--字符串,對象屬性

default--默認返回值,如果不提供該參數,在沒有對于屬性時,將觸發AttributeError。

返回值:

返回對象屬性值

class People:  country='China'  def __init__(self,name):    self.name=name  def people_info(self):    print('%s is xxx' %(self.name))obj=getattr(People,'country')print(obj)#返回值China#obj=getattr(People,'countryaaaaaa')#print(obj)#報錯# File "/getattr()函數.py", line 32, in <module>#   obj=getattr(People,'countryaaaaaa')# AttributeError: type object 'People' has no attribute 'countryaaaaaa'obj=getattr(People,'countryaaaaaa',None)print(obj)#返回值None

setattr()函數

描述:

setattr函數,用于設置屬性值,該屬性必須存在

語法:

setattr(object,name,value)

參數:

object--對象

name--字符串,對象屬性

value--屬性值

返回值:

class People:  country='China'  def __init__(self,name):    self.name=name  def people_info(self):    print('%s is xxx' %(self.name))obj=People('aaa')setattr(People,'x',111) #等同于People.x=111print(People.x)#obj.age=18setattr(obj,'age',18)print(obj.__dict__)#{'name': 'aaa', 'age': 18}print(People.__dict__)#{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}

delattr()函數

描述:

delattr函數用于刪除屬性

delattr(x,'foobar)相當于del x.foobar

語法:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 积石山| 大兴区| 丹阳市| 镶黄旗| 土默特右旗| 磴口县| 庄河市| 尚义县| 乐业县| 吉林市| 称多县| 元氏县| 宁德市| 汝州市| 荆门市| 乌兰察布市| 周至县| 香港 | 阿瓦提县| 平阳县| 高碑店市| 绥中县| 营山县| 阳泉市| 从江县| 大洼县| 仪征市| 江达县| 武乡县| 郑州市| 扶余县| 上杭县| 饶河县| 临朐县| 民县| 锡林浩特市| 泸州市| 邵阳市| 哈巴河县| 静安区| 吴川市|