Python getattr()関数
例
「Person」オブジェクトの「age」プロパティの値を取得します。
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 |
その他の例
例
属性が存在しない場合にメッセージを書き込むには、「default」パラメーターを使用します。
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'page', 'my message')
関連ページ
属性を削除するためのdelattr()関数
hasattr ()関数、属性が存在するかどうかを確認します
属性の値を設定するためのsetattr()関数