Skip to content

Instantly share code, notes, and snippets.

@niconico25
Created May 10, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niconico25/bc8935527dc410e77a467804129a03e8 to your computer and use it in GitHub Desktop.
Save niconico25/bc8935527dc410e77a467804129a03e8 to your computer and use it in GitHub Desktop.
#
# そのまま対話モード >>> に
# コピペで実行できます。
#
#
# 浅いコピー copy と深いコピー deepcopy の違いを示します。
#
import copy
import json
#
# 再帰的に identity を表示する関数
# Effective Python item 26 を参考にしました。
# http://bit.ly/2HgJAyr
#
def ids(identifier):
# list
if isinstance(identifier, list):
iterator = enumerate(identifier)
# dict
elif isinstance(identifier, dict):
iterator = identifier.items()
# object mutable
elif hasattr(identifier, '__dict__'):
iterator = identifier.__dict__.items()
# object immutable
else:
return id(identifier)
return id(identifier),\
{attribute: ids(value) for attribute, value in iterator}
#
# サンプルクラス
#
class Computer:
def __init__(self, cpu, primary_memory, auxiliary_memory):
self.cpu = cpu
self.primary_memory = primary_memory
self.auxiliary_memory = auxiliary_memory
class Cpu:
def __init__(self, clock, core):
self.clock = clock
self.core = core
class Memory:
def __init__(self, volume, clock, type_):
self.volume = volume
self.clock = clock
self.type_ = type_
class Ssd:
def __init__(self, volume):
self.volume = volume
#
# サンプルコード
#
#
# 2つのコピーの違いを示すために
# identity がどのように変化するかを表示します。
#
# 浅いコピー copy.copy
# 変数に束縛されたインスタンスだけを
# 新しくインスタンス化けるします。
#
# 深いコピー copy.deepcopy
# 変数や再帰的に属性に束縛されたインスタンを全て
# 新しくインスタンス化します。
# ただし、変更できないオブジェクトを除きます。
#
computer = Computer(
Cpu('2.3GHz', 5),
Memory('8GB', '2133MHz', 'DDR4'),
Ssd('256GB'))
# original
print(json.dumps(ids(computer), indent=4))
# copy
print(json.dumps(ids(copy.copy(computer)), indent=4))
# deecomputeropy
print(json.dumps(ids(copy.deepcopy(computer)), indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment