0

This may be a dumb question but it has been awhile since I have worked with python...

So, I have a set of objects, for example:

p1 = Person("Name", "Age")
p2 = Person("Name", "Age")
..

How can I, essentially, copy one object and put it in an empty object?

2

1 Answer 1

1

'Empty' objects don't really exist but for demonstration purposes let's say empty is None.

Onwards, you can 'copy' them and you can do it two different ways:

  • Via the assignment statement where the names of the "copied" objects all reference the same object
  • Via copy.deepcopy where 'copied' objects are different (from an id() aspect) but they have similar contents.

Either way, it ain't even hard.

For the first case, we use a simple assignment statement, given a simple class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

And two instances of it:

p1 = Person("Name1", "Age1")
p2 = Person("Name2", "age2")

Having a new "empty" object p3 = None, we can copy another objects reference to it via the assignment operator:

p3 = p1  # p1 and p3 point to the same Person Instance

print(p3.name)  # 'Name1'
print(p3 is p1)  # True, same object

# Changes we make to a copy are visible to other copies.
p3.name = "Change name"  
p1.name   # 'Change name'

To make a copy of an object, meaning identical from a content aspect we can use copy.deepcopy:

from copy import deepcopy

# copy contents of p3
p4 = copy.deepcopy(p3) 

print(p4.name) # prints "Change name"

# changes now are insulated to p4.
p4.name = " Another name"
print(p3.name)  # print 'Change name'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.