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

วิธีรู้ว่า Object มี Attribute ใน Python

เราสามารถใช้ฟังก์ชัน hasattr() หาว่า Python Object obj มี Attribute หรือ Property מסוים หรือไม่

hasattr(obj, 'attribute')

Convention ใน Python คือ ถ้า Property น่าจะอยู่ ให้เรียกมันเลยและ Catch ด้วย Try/Except Block ถ้า Property น่าจะไม่อยู่ หรือไม่แน่ใจ ใช้ hasattr จะเป็นตัวเลือกที่ดีกว่า

โค้ดต่อไปนี้แสดงวิธีเช็คว่า Class foo มี Attribute 'a' หรือไม่

ตัวอย่าง

class foo:
    a = 54
    def bar(self):
        pass

if hasattr(foo, 'a'):
    print foo.a
else:
    print 'No such attribute'

Output

54