新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python hasattr()
hasattr()方法有助于檢查給定的對(duì)象是否具有指定的屬性。如果屬性存在,則返回 true,否則返回 false。

**hasattr(object, name) **#Where object,name shows object name and attribute name respectively.
hasattr()參數(shù):
取 3 個(gè)參數(shù)。getattr()調(diào)用hasattr()方法,檢查是否要引發(fā)屬性錯(cuò)誤。getattr()用于獲取指定對(duì)象的屬性值。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標(biāo) | 要檢查其命名屬性的對(duì)象 | 需要 |
| 名字 | 要搜索的屬性的名稱 | 需要 |
hasattr()返回值
返回值取決于getattr()函數(shù)。如果它引發(fā)了屬性錯(cuò)誤,則返回假。否則,返回真。
| 投入 | 返回值 | | 對(duì)象具有給定的命名屬性 | 真實(shí)的 | | 對(duì)象沒有給定的命名屬性 | 錯(cuò)誤的 |
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 分享題目:創(chuàng)新互聯(lián)Python教程:Python hasattr()
地址分享:http://www.dlmjj.cn/article/djiddco.html


咨詢
建站咨詢
