跳至主要內容

hasattr()

Python 中的 hasattr() 函式 是一個內建函式,如果指定物件具有給定的屬性,則傳回 True,否則傳回 False。它需要兩個參數:一個物件和一個代表屬性名稱的字串。此函式通常用於在嘗試存取物件之前,檢查物件是否具有特定屬性。

參數值

參數 說明
object

檢查其屬性存在的 物件

name

代表要檢查是否存在之屬性名稱的 字串

傳回值

hasattr() 函式傳回一個 布林值,可能是 TrueFalse

如何在 Python 中使用 hasattr()

範例 1

Python 中的 hasattr() 函式 用於判斷物件是否具有指定的屬性。

class Person:
    name = 'Alice'
    age = 30

print(hasattr(Person, 'name'))  # Output: True
print(hasattr(Person, 'gender'))  # Output: False
範例 2

如果物件具有給定的屬性,則傳回 True,否則傳回 False

class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

car = Vehicle('Toyota', 'Corolla')
print(hasattr(car, 'make'))  # Output: True
print(hasattr(car, 'color'))  # Output: False
範例 3

hasattr() 函式也可用于檢查物件是否具有特定方法。

class Calculator:
    def add(self, x, y):
        return x + y

calc = Calculator()
print(hasattr(calc, 'add'))  # Output: True
print(hasattr(calc, 'subtract'))  # Output: False