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

首頁 > 編程 > Python > 正文

詳解Python3 中hasattr()、getattr()、setattr()、delattr()函數(shù)

2019-11-02 14:09:55
字體:
供稿:網(wǎng)友

hasattr()函數(shù)

hasattr()函數(shù)用于判斷是否包含對應(yīng)的屬性

語法:

hasattr(object,name)

參數(shù):

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()函數(shù)

描述:

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

語法:

getattr(object,name,default)

參數(shù):

object--對象

name--字符串,對象屬性

default--默認(rèn)返回值,如果不提供該參數(shù),在沒有對于屬性時(shí),將觸發(fā)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)#報(bào)錯(cuò)# File "/getattr()函數(shù).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()函數(shù)

描述:

setattr函數(shù),用于設(shè)置屬性值,該屬性必須存在

語法:

setattr(object,name,value)

參數(shù):

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()函數(shù)

描述:

delattr函數(shù)用于刪除屬性

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

語法:

setattr(object,name)

參數(shù):

object--對象

name--必須是對象的屬性

返回值:

示例:

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 永泰县| 鹤壁市| 西峡县| 麻栗坡县| 平原县| 德钦县| 峨眉山市| 策勒县| 秦皇岛市| 堆龙德庆县| 运城市| 南江县| 平罗县| 潮州市| 香港| 泾川县| 平陆县| 沈阳市| 高雄市| 镇平县| 阳江市| 宝丰县| 曲沃县| 蓬安县| 雷山县| 黎川县| 五寨县| 伊川县| 朝阳市| 鹤壁市| 保山市| 神池县| 斗六市| 泗水县| 临颍县| 德江县| 六安市| 石渠县| 祥云县| 雷山县| 雷山县|