Python hasattr ()ฟังก์ชัน
ตัวอย่าง
ตรวจสอบว่าวัตถุ "บุคคล" มีคุณสมบัติ "อายุ" หรือไม่:
class Person:
name = "John"
age = 36
country = "Norway"
x = hasattr(Person, 'age')
ความหมายและการใช้งาน
ฟังก์ชันhasattr()
จะคืนค่า
True
หากอ็อบเจ็กต์ที่ระบุมีแอตทริบิวต์ที่ระบุ มิFalse
ฉะนั้น
ไวยากรณ์
hasattr(object, attribute)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
object | Required. An object. |
attribute | The name of the attribute you want to check if exists |
หน้าที่เกี่ยวข้อง
ฟังก์ชันdelattr()เพื่อลบแอตทริบิวต์
ฟังก์ชันgetattr()เพื่อรับค่าของแอตทริบิวต์
ฟังก์ชันsetattr()เพื่อตั้งค่าแอตทริบิวต์