Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน hasattr() ใน Python ทำอะไร

hasattr() Method

คืน True หาก Object มี Named Attribute ที่กำหนด False หากไม่มี

Syntax

hasattr(object, name)

hasattr() ถูกเรียกโดย getattr() เพื่อเช็คว่าจะ Raise AttributeError หรือไม่

Parameters: Object, Attribute Name

Returns: True (มี Attribute), False (ไม่มี Attribute)

ตัวอย่าง

class Male:
    age = 21
    name = 'x'

x = Male()
print('Male has age?:', hasattr(x, 'age'))      # True
print('Male has salary?:', hasattr(x, 'salary')) # False