Reputation: 31
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?
Upvotes: 3
Views: 6917
Reputation: 10695
Although you cannot modify the input parameter cstring1 in
def strcpy(cstring1,cstring2):
import copy
cstring1=copy.copy(cstring2)
there are other things you can do to accomplish your goal.
First, you could make strcpy
part of the string class, and let that member function update its own str
element.
Second, you could provide CString
set and get functions. These functions could be used directly to copy one string to another, or they could be used by the member function that performs the string copy.
Python is an interesting language. It contains a lot of elements that make it seem like a regular imperative language like C or Perl, and you can construct a lot of code that looks like C. In terms of Python pureness, you'll be guided along the way not to do things in Python thinking like you're programming in C.
I suggest re-creating something like strcpy can be best accomplished by solving the problem `a la Python instead. For starters, one string can simply replace another.
Good luck.
Upvotes: 1
Reputation: 19329
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.
Upvotes: 5