Python3内置函数详解:hasattr、getattr、setattr与delattr的用法及示例
本文详细解析Python3中用于对象属性管理的四个核心内置函数:hasattr、getattr、setattr和delattr。通过具体语法说明、参数定义及完整代码示例,展示如何判断属性存在、获取属性值、动态设置属性以及安全删除属性,帮助开发者高效处理Python对象的状态管理。
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'))
#返回值:True
print('country' in People.__dict__)
#返回值:True
print(hasattr(obj,'people_info'))
#返回值:True
print(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=111
print(People.x)
#obj.age=18
setattr(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。
语法:
setattr(object,name)
参数说明如下:
object:目标对象。
name:必须是对象中存在的属性名。
返回值说明:
无返回值。
示例:
class People:
country='China'
def __init__(self,name):
self.name=name
def people_info(self):
print('%s is xxx' %(self.name))
delattr(People,'country') #等同于del People.country
print(People.__dict__)
{'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
补充示例:
class Foo:
def run(self):
while True:
cmd=input('cmd>>: ').strip()
if hasattr(self,cmd):
func=getattr(self,cmd)
func()
def download(self):
print('download....')
def upload(self):
print('upload...')
# obj=Foo()
# obj.run()
总结
以上内容介绍了Python3中hasattr()、getattr()、setattr()及delattr()四个函数的详细用法与示例代码,旨在帮助读者掌握对象属性的动态管理技巧。如有任何疑问,欢迎留言交流,小编将及时回复。感谢对本站的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













