當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python hasattr方法用法及代碼示例

Python 的 hasattr(~) 方法返回 Boolean 指示提供的對象是否具有指定的屬性。

參數

1. object | object

我們正在檢查屬性的對象。

2. name | string

表示我們正在檢查的屬性名稱的字符串。

例子

檢查對象 my_cat 是否具有屬性 age

class Cat():
 # This is constructor for python
 def __init__(self, name, age):
        self.name = name
        self.age = age
 # Teaching each cat how to meow
 def meow(self):
 print("I am a " + str(self.age) + " year old " + self.name)
# Creating an instance my_cat representing my cat Roxas
my_cat = Cat("Roxas", 26)
hasattr(my_cat, "age")



True

檢查對象 my_cat 是否具有屬性 height

hasattr(my_cat, "height")



False

相關用法


注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | hasattr method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。