参数传入有两种:
1.passing by value
2.passing by reference
C++ can pass-by-value and pass-by-reference
Straightforward. You can simulate pass-by-reference with pointers. eg:void grow(int& age){}it's easier to write a swap method this way.
Java is pass-by-value
Primitive Types (non-object built-in types) are simply passed by value. Passing Object References feels like pass-by-reference, but it isn't. What you are really doing is passing references-to-objects by value.
OK, so what about Python?
Python passes references-to-objects by value (like Java), and everything in Python is an object. This sounds simple, but then you will notice that some data types seem to exhibit pass-by-value characteristics, while others seem to act like pass-by-reference... what's the deal?
It is important to understand mutable and immutable objects. Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed. Other objects, like lists and dictionaries are mutable, which means you can change the object in-place. Therefore, altering an object inside a function/method will also change the original object outside.
python中string是immutable的,那么如何实现自己的mutable string 呢?
class MutableString(object):
def __init__(self, data):
self.data = list(data)
def __repr__(self):
return "".join(self.data)
def __setitem__(self, index, value):
self.data[index] = value
def __getitem__(self, index):
if type(index) == slice:
return "".join(self.data[index])
return self.data[index]
def __delitem__(self, index):
del self.data[index]
def __add__(self, other):
self.data.extend(list(other))
def __len__(self):
return len(self.data)