1

How would I copy all the properties of a class to a new instance of the class. In the example below, with the way python works, when I use b=a, it assigns b and a to the same memory address. When i make a change to "b" the change is also made to "a." Both elements of the list are stored at the same address

class test:

    def __init__(self, name="Name",data=[]):
        self.name=name
        self.data=data




list=[]
a = test("First Name",["DATA1","DATA2","DATA3"])
b=a
list.append(a)
list.append(b) 

I'm wanting to achieve something similar to how the list class allows you to do this to copy the list to a new memory address.

list1=[1,2,3]
list2=list(list1)

So in my case.

a = test("First Name",["DATA1","DATA2","DATA3"])
b=test(a)

without having to

b=test(a.name,a.data)

EDIT

Id like to achive the same effect as

 b=copy.deepcopy(a)

but through this usage.

b=test(a)
Bigbob556677
  • 1,805
  • 1
  • 13
  • 38
  • Possible duplicate of [Copy constructor in python](https://stackoverflow.com/questions/1241148/copy-constructor-in-python) – Maciej Jureczko Aug 29 '17 at 14:47
  • copy works for what I need but id like to achieve the same result without copy. just like how the list class uses list2=list(list1) id like to be able to b=test(a) – Bigbob556677 Aug 29 '17 at 14:53

3 Answers3

0

Use copy:

import copy
b = copy.deepcopy(a)
Stuart
  • 6,630
  • 2
  • 24
  • 40
  • well actually. Though that achieved the result I wanted. how would I write my class to work similar to the list2=list(list1) where b=test(a) without using the copy class. – Bigbob556677 Aug 29 '17 at 14:51
0

You may want to write a copy constructor. For example...

import copy

class Foo:

  def __init__(self, data):
    self._data = data

  @classmethod
  def from_foo(cls, class_instance):
    data = copy.deepcopy(class_instance._data)
    return cls(data)
Maciej Jureczko
  • 1,560
  • 6
  • 19
  • 23
0

This achieved what I was wanting to do.

class Test:
    def __init__(self, arg):
        if isinstance(somearg, self.__class__):
            self.__dict__ = somearg.__dict__.copy()
        else:
            self.var = arg

Usage:

a=Test(123)
b=Test(a)
Bigbob556677
  • 1,805
  • 1
  • 13
  • 38