0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラスのオブジェクトの属性をfor文で追加する

Last updated at Posted at 2020-11-11

オブジェクトの属性を複数作りたいときは組み込み関数setattrを使うことができます。
引数は属性の追加先オブジェクト、属性名、値の3つです。

import numpy as np

class Test:
    pass

test = Test()
for i in range(10):
    setattr(test, 'var' + str(i), np.random.randint(10))

print(test.var5)

for name, value in test.__dict__.items():
    print(f'{name} : {value}')

出力
2
var0 : 2
var1 : 6
var2 : 2
var3 : 1
var4 : 2
var5 : 2
var6 : 7
var7 : 2
var8 : 7
var9 : 4
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?