hasattr()
hasattr() 函数用来判断某个类实例对象是否包含指定名称的属性或方法。
该函数的语法格式如下:
hasattr(obj, name)
其中 obj 指的是某个类的实例对象,name 表示指定的属性名或方法名,返回BOOL值,有name特性返回True, 否则返回False。
例子:
1
2
3
4
5
6
7
8
9
|
class demo: def __init__ ( self ): self .name = "lily" def say( self ): print ( "say hi" ) d = demo() print ( hasattr (d, 'name' )) print ( hasattr (d, 'say' )) print ( hasattr (d, 'eat' )) |
运行结果如下:
True
True
False
getattr()
getattr() 函数获取某个类实例对象中指定属性的值。
该函数的语法格式如下:
getattr(object, name[, default])
其中,obj 表示指定的类实例对象,name 表示指定的属性名,而 default 是可选参数,用于设定该函数的默认返回值,即当函数查找失败时,如果不指定 default 参数,则程序将直接报 AttributeError 错误,反之该函数将返回 default 指定的值。
例子:
1
2
3
4
5
6
7
8
9
|
class demo: def __init__ ( self ): self .name = "lily" def say( self ): return "say hi" d = demo() print ( getattr (d, 'name' )) print ( getattr (d, 'say' )) print ( getattr (d, 'eat' )) |
运行结果如下:
lily
<bound method demo.say of <__main__.demo object at 0x7f31c630d0a0>>
Traceback (most recent call last):
File "/test.py", line 11, in <module>
print(getattr(d, 'eat'))
AttributeError: 'demo' object has no attribute 'eat'
可以看到,对于类中已有的属性,getattr() 会返回它们的值,而如果该名称为方法名,则返回该方法的状态信息;反之,如果该明白不为类对象所有,要么返回默认的参数,要么程序报 AttributeError 错误。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,可以在后面添加一对括号。比如:
1
2
3
4
5
6
7
8
9
10
11
12
|
class demo: def __init__ ( self ): self .name = "lily" def say( self ): return "say hi" def eat( self , something): return f "eat {something}" d = demo() print ( getattr (d, 'name' )) print ( getattr (d, 'say' )) print ( getattr (d, 'eat' )( 'apple' )) print ( getattr (d, 'eat' , 'no eat' )( 'banana' )) |
运行结果如下:
lily <bound method demo.say of <__main__.demo object at 0x7fe99b1ca0a0>> eat apple eat banana
setattr()
setattr() 函数最基础的功能是修改类实例对象中的属性值。其次,它还可以实现为实例对象动态添加属性或者方法。
该函数的语法格式如下:
setattr(obj, name, value)
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class demo: def __init__ ( self ): self .name = "lily" d = demo() print ( getattr (d, 'name' )) print ( '----------' ) setattr (d, 'name' , 'tom' ) print ( getattr (d, 'name' )) print ( '----------' ) print ( hasattr (d, 'age' )) setattr (d, 'age' , '18' ) print ( hasattr (d, 'age' )) print ( getattr (d, 'age' )) |
运行结果如下:
lily
----------
tom
----------
False
True
18
到此这篇关于一文搞懂Python的hasattr()、getattr()、setattr() 函数用法的文章就介绍到这了,更多相关Python的hasattr()、getattr()、setattr() 函数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/zyy247796143/article/details/124334886