🐡

Python100本ノック#2 オブジェクトの属性(attribute)

2023/11/27に公開

オブジェクトの属性(attribute)とは

Pythonにおいてすべてのオブジェクトは属性(attribute)とメソッド(method)を持っている。
属性は「特徴」であり、例えば人間の名前、身長、体重などがオブジェクトの属性である。
車の車両番号、色、メーカー、燃費などが属性になる。

クラスの外部から属性を追加、取得

属性の追加

オブジェクト名.属性名 =

# 1、Personクラスを定義
class Person():
    pass

# 2、Person类のインスタンス化、p1を作成
p1 = Person()
# 3、p1の属性を追加
p1.name = 'Kobayashi'
p1.age = 99
p1.address = '東京都新宿区...'

属性の取得

オブジェクト名.属性名

print(f'名前:{p1.name}')
print(f'年齢:{p1.age}')
print(f'住所:{p1.address}')

クラスの内部から属性の取得

self.属性名

class Person():
    def speak(self):
        print(f'名前:{self.name},年齢:{self.age},住所:{self.address}')

p1 = Person()
p1.name = 'Kobashiya'
p1.age = 99
p1.address = '東京都新宿区...'
p1.speak()

マジックメソッド(Magic Method)

__XXX___のメソッドはマジックメソッドといい、特殊機能を持つため特殊メソッド(Special method)と呼ぶことが多い。

上記のようにオブジェクトをインスタンス化した後に属性を追加して設定するのは非効率なやり方である。インスタンス化の際に属性を設定する(初期値設定)には、__init___を利用できる。

マジックメソッドの確認方法

>>> print(dir(int))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '
__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstat
e__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', 
'__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__
rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '
__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '
__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_lengt
h', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Discussion