Python – Copy object in Python

copyobjectpython

I'm new to Python, so I tried writing a class to emulate string functions in C:

class CString:

  def __init__(self,str):
        self.value=[]
        self.value.extend(list(str))

def strcpy(cstring1,cstring2):
      import copy
      cstring1=copy.copy(cstring2)

def puts(cstring1):
    print ''.join(cstring1.value)

But strcpy doesn't seem to be working:

>>obj1=CString("Hello World")
>>obj2=CString("Hai World!")
>>puts(obj1)
Hello World!
>>puts(obj2)
Hai World!
>>strcpy(obj1,obj2)
>>puts(obj1)
Hello World!

Am I assigning copy.copy(cstring2) wrongly?

Best Answer

The line

cstring1 = copy.copy(cstring2)

only changes the local variable called cstring1, it does not change the variable in the outer scope called obj1.

Have a look at this other stackoverflow question for more information.