Python: How do I pass a string by reference?

前端 未结 7 1071
清歌不尽
清歌不尽 2020-12-05 18:21

From this link: How do I pass a variable by reference?, we know, Python will copy a string (an immutable type variable) when it is passed to a function as a parameter, but I

7条回答
  •  一生所求
    2020-12-05 18:51

    wrapping the string into a class will make it pass by reference:

        class refstr:
           "wrap string in object, so it is passed by reference rather than by value"
           def __init__(self,s=""):
              self.s=s
           def __add__(self,s):
              self.s+=s
              return self
           def __str__(self):
              return self.s
    
        def fn(s):
           s+=" world"
    
        s=refstr("hello")
        fn(s) # s gets modified because objects are passed by reference
        print(s) #returns 'hello world' 
    

提交回复
热议问题