How to skip initialization when copying objects in python?

I want to implement my own copy method for class A that looks like this:

class A(object):
    def __init__(self):
        self.field1 = generate_a_list_of_ints()
    def __copy__(self):
        result = A()
        result.fiel1[:] = self.field1[:]
        return result

      

The problem with the above code is that when copying object A, the initialization code will be called, even if there is no need to get the initial values.

How to copy field1 without running init code? I have searched for information on __new__

, but most of it was about factories and things that seemed to be unrelated, so I'm still not clear on how to skip initialization.

+3


source to share


1 answer


I suggest an optional argument in your method __init__()

, for example:



class A(object):
    def __init__(self, init=True):
        if init:
            self.field1 = generate_a_list_of_ints()
    def __copy__(self):
        result = A(init=False)
        result.fiel1[:] = self.field1[:]
        return result

      

+2


source







All Articles