美图齐众专注资阳网站设计 资阳网站制作 资阳网站建设
资阳网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

创新互联Python教程:Python hasattr()

hasattr()方法有助于检查给定的对象是否具有指定的属性。如果属性存在,则返回 true,否则返回 false。

 **hasattr(object, name)  **#Where object,name shows object name and attribute name respectively. 

hasattr()参数:

取 3 个参数。getattr()调用hasattr()方法,检查是否要引发属性错误。getattr()用于获取指定对象的属性值。

参数描述必需/可选
目标要检查其命名属性的对象需要
名字要搜索的属性的名称需要

hasattr()返回值

返回值取决于getattr()函数。如果它引发了属性错误,则返回假。否则,返回真。

| 投入 | 返回值 | | 对象具有给定的命名属性 | 真实的 | | 对象没有给定的命名属性 | 错误的 |

Python 中hasattr()方法的示例

示例hasattr()在 Python 中是如何工作的?

 class Person:
    age = 23
    name = 'Adam'
 pers

print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary')) 

输出:

Person has age?: True
Person has salary?: False

示例hasattr()如何使用示例?

 class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

d = Employee(10, 'Pankaj')

if hasattr(d, 'name'):
    print(getattr(d, 'name')) 

输出:

Pankaj

示例hasattr()如何返回布尔值?

 class Employee:  
    age = 21  
    name = 'Phill'  

employee = Employee()  

print('Employee has age?:', hasattr(employee, 'age'))  
print('Employee has salary?:', hasattr(employee, 'salary')) 

输出:

Employee has age?: True
Employee has salary?: False

分享名称:创新互联Python教程:Python hasattr()
当前链接:http://www.zsjierui.cn/article/djiddco.html

其他资讯