الدالة Python getattr ()
مثال
احصل على قيمة خاصية "age" لكائن "Person":
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'age')
التعريف والاستخدام
ترجع getattr()
الدالة قيمة السمة المحددة من الكائن المحدد.
بناء الجملة
getattr(object, attribute, default)
قيمه المعامل
Parameter | Description |
---|---|
object | Required. An object. |
attribute | The name of the attribute you want to get the value from |
default | Optional. The value to return if the attribute does not exist |
مزيد من الأمثلة
مثال
استخدم المعلمة "الافتراضية" لكتابة رسالة عندما لا تكون السمة موجودة:
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'page', 'my message')
الصفحات ذات الصلة
الدالة delattr () لإزالة سمة
دالة hasattr () للتحقق من وجود سمة
الدالة setattr () ، لتعيين قيمة السمة