Why does Python's copy.copy() return a object not equal to the original? -
in python, if copy list or dictionary, copied instance equal original:
>>> = [1, 2, 3] >>> b = copy.copy(a) >>> == b true >>> = {"a":1, "b":2} >>> b = copy.copy(a) >>> == b true
but if copy object, result not equal original:
>>> class myclass(): ... def __init__(self, name): ... self._name= name ... >>> = myclass('a') >>> b = copy.copy(a) >>> == b false
why?
equality in python objects checked calling __eq__()
function.
example:
>>> class ca: ... def __eq__(self, other): ... print("equals") ... return true ... >>> c = ca() >>> b = ca() >>> c == b equals true
that because list
equality dependent on elements , not actual memory location (reference) list stored, is, can 2 different list references, if have same elements in same order, lists equal.
example:
>>> l = [1,2] >>> l1 = [1,2] >>> id(l) 2830504 >>> id(l1) 2831864 >>> l == l1 true
but custom class, have not overwritten __eq__()
, hence call __eq__()
of parent class, object
, , checks equality based on reference.
and when copy.copy()
shallow copying, is, creates new instance object members (attributes, etc.) remaining same. hence, unequal (as different references/different instances).
if want myclass
check equality based on self._name
, have overwrite __eq__()
function that.
you can find more information comparisons here.
Comments
Post a Comment