Python - 文法 - 属性(attribute)


クラウディア 


1. 概要
2. getattr
3. hasattr
4. dir

1. 概要

 「python」のオブジェクトは、属性(attribute)というものを持っていて、それを使って操作することがあります。  本ページは、下記のサイトを参考にさせていただきました。
組み込み関数」
「属性の有無チェック (hasattr) 

2. getattr


class myClass:
  def __init__(self):
    self.status = 0
    pass
 というクラスを定義しまして。  このクラスには、「status」という「attribute」があるわけで。  このクラスのインスタンスに「.status」とつけるか、「getattr()」という組み込み関数をつかって、「status」を取得することができます。  上に続けて。

a = myClass()

print(a.status)
print(getattr(a, 'status'))
 というコードを書くと。

0
0
 という結果が得られます。  「attribute」がないときは、エラーになります。

print(getattr(a, 'code'))
 を実行すると、下記のようになります。

Traceback (most recent call last):
  File "d:\101-sing.ne.jp\home\hogehoge\lang\python\sample\attribute01.py", line 10, in 
    print(getattr(a, 'code'))
          ^^^^^^^^^^^^^^^^^^
AttributeError: 'myClass' object has no attribute 'code'
 「getattr()」の第三引数を設定すると、「attribute」がないときの結果を設定することができます。

print(getattr(a, 'code', 'no code'))
 を実行すると、下記の結果が得られます。

no code

3. hasattr

 「hasattr()」組み込み関数で、オブジェクトが「attribute」を持っているか確認できます。

b = 1

print(hasattr(a, 'status'))
print(hasattr(b, 'status'))
 を実行すると、下記の結果が得られます。

True
False

4. dir

 「dir()」組み込み関数で、オブジェクトの持つ、メソッドと「attribute」の一覧を取得できます。  冒頭で、定義した、クラスのインスタンスを取得後。

print(dir(a))
 を記述して、実行すると、下記の結果が得られます。

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'status']

AbemaTV 無料体験