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

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

Python getattr()

คืนค่าของ Named Attribute ของ Object หาไม่เจอ คืน Default Value ที่ให้มา

Syntax

getattr(object, name[, default])

Parameters: Object, Attribute Name, Default (Optional)

Returns: Attribute Value, หรือ Default, หรือ Raise AttributeError หากไม่มี Default

ตัวอย่าง

class Male:
    age = 21
    name = "Abel"

x = Male()
print('The age is:', getattr(x, "age"))
print('The age is:', x.age)

ผลลัพธ์

The age is: 21
The age is: 21