LoginSignup
4
1

More than 5 years have passed since last update.

pythonでクラスオブジェクトをコピーすることはできない

Posted at

当たり前と言えば当たり前の話なのですが…

In [1]: class A:
   ...:     pass
   ...: 

In [2]: a1 = A(); a2 = A(); a3 = A()

In [3]: print(id(a1), id(a2), id(a3))
4420780664 4420780776 4420781896

普通にオブジェクトを3つ生成すると、このように区別して生成されます。

pythonだと、クラスすらオブジェクトなのでひょとしてA自体コピーすることができる?と思ってcopyモジュールを使ってやってみました。

In [4]: import copy

In [5]: ac1 = A; ac2 = copy.copy(A); ac3 = copy.copy(A)

In [6]: print(id(ac1), id(ac2), id(ac3))
140280656452216 140280656452216 140280656452216

In [7]: ac1 = A; ac2 = copy.deepcopy(A); ac3 = copy.deepcopy(A)

In [8]: print(id(ac1), id(ac2), id(ac3))
140280656452216 140280656452216 140280656452216

ご覧のとおり、Aは1つしか生成できないようです。言語仕様としてはこれで全く正しいと感じました。

4
1
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
4
1