3

I want to implement my own copy method for a class A which 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 code above is that when copying an A object, the initialization code will be invoked even though there is no need to get the initial values.

How can I copy the field1 without running initialization code? I looked for information about __new__ but most of it was referring to factories and stuff that seemed unrelated, so it's still unclear to me how to skip the initialization.

georg
  • 211,518
  • 52
  • 313
  • 390
Abdallah
  • 335
  • 1
  • 7

1 Answers1

3

I suggest an optional argument in your __init__() method, like so:

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
steveha
  • 74,789
  • 21
  • 92
  • 117