fork(2) download
  1. from copy import deepcopy
  2.  
  3. class Foo: pass
  4.  
  5. foo = Foo()
  6. foo.bar = 10
  7. shallow_copies = [foo for _ in range(10)] # todos partilham as mesmas referencias, o mesmo foo e partilhado
  8. deep_copies = [deepcopy(foo) for _ in range(10)] # copias independentes, referencias diferentes
  9.  
  10. shallow_copies[0].bar = 100 # mudar valor da propriedade de foo
  11. deep_copies[0].bar = 100 # mudar valor da propriedade de foo
  12.  
  13. print([f.bar for f in shallow_copies]) # [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
  14. print([f.bar for f in deep_copies]) # [100, 10, 10, 10, 10, 10, 10, 10, 10, 10]
  15. print(all((f.bar is shallow_copies[0].bar) for f in shallow_copies[1:])) # True , todos os foo tem bar com a mesma ref
  16. print(all((f.bar is deep_copies[0].bar) for f in deep_copies[1:]))
Success #stdin #stdout 0.01s 28384KB
stdin
Standard input is empty
stdout
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
[100, 10, 10, 10, 10, 10, 10, 10, 10, 10]
True
False