2

I have a class defined as follows:

class Table:
    order = {}
    id = None
    state = None

I have a dictionary which contains the key value pairs which has key indices and values are table objects.

dict{1: table_object}

Now I want to get the table object and copy the details to another object, something like:

new_object = dict[1]

How do I change the class or copy the details to another object?

praxmon
  • 5,009
  • 22
  • 74
  • 121
  • So, you are changing the class attribute at the instance level, and you want to make sure it gets applied to all other instances? – idjaw Nov 08 '16 at 03:21
  • I just want the same value to be present in the new object that I have made – praxmon Nov 08 '16 at 03:38
  • 1
    While Andrew's answer below is correct, you almost never have to copy objects in Python. Most of the time that beginners think they need a copy they are not understanding the data model. Try explaining to your mouse why you *need* to, you'll probably find you don't. – msw Nov 08 '16 at 03:39

1 Answers1

3

If you want to create a copy of the class and assign that to a new object, you can use copy:

from copy import copy

new_object = copy(dict[1])

Depending on the structure of your class, you may want to do a deepcopy instead. A shallow copy will only copy references to the objects found in your initial class. A deepcopy will attempt to recursively copy all objects within your original class. There can be issues with this if you have some recursive structure within your classes, but for the most part this won't be an issue.

from copy import deepcopy

new_object = deepcopy(dict[1])

See this for more info - https://docs.python.org/2/library/copy.html

Andrew Guy
  • 9,310
  • 3
  • 28
  • 40