国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 山东| 通化市| 鄢陵县| 且末县| 南澳县| 高淳县| 增城市| 神农架林区| 会泽县| 南阳市| 固始县| 江津市| 桂林市| 新乡县| 瑞金市| 门头沟区| 贵阳市| 三明市| 册亨县| 甘德县| 绩溪县| 夹江县| 盱眙县| 巫溪县| 娱乐| 论坛| 宜兰市| 专栏| 和平区| 长寿区| 河池市| 云和县| 安平县| 儋州市| 桦南县| 天全县| 德令哈市| 克什克腾旗| 宁陕县| 房山区| 仲巴县|