python: unintentionally modifying parameters passed into a function

前端 未结 4 831
死守一世寂寞
死守一世寂寞 2021-02-04 10:05

A few times I accidentally modified the input to a function. Since Python has no constant references, I\'m wondering what coding techniques might help me avoid making this mista

4条回答
  •  余生分开走
    2021-02-04 10:48

    You can use a metaclass as follows:

    import copy, new
    class MakeACopyOfConstructorArguments(type):
    
        def __new__(cls, name, bases, dct):
            rv = type.__new__(cls, name, bases, dct)
    
            old_init = dct.get("__init__")
            if old_init is not None:
                cls.__old_init = old_init
                def new_init(self, *a, **kw):
                    a = copy.deepcopy(a)
                    kw = copy.deepcopy(kw)
                    cls.__old_init(self, *a, **kw)
    
            rv.__init__ = new.instancemethod(new_init, rv, cls)
            return rv
    
    class Test(object):
        __metaclass__ = MakeACopyOfConstructorArguments
    
        def __init__(self, li):
            li[0]=3
            print li
    
    
    li = range(3)
    print li
    t = Test(li)
    print li
    

提交回复
热议问题