3

I have this initialiser for a line class in Python and it takes two points as a parameter. The problem is my initialiser is only copying the references. So self.point0 and point 0 are pointing to the same object. I am not really sure how to change that so that I am not just copying the reference. Line class:

def __init__(self, point0, point1): 
    self.point0 = point0
    self.point1 = point1

Point class:

def __init__(self, x, y):
    self.x = x
    self.y = y
3
  • 1
    Any particular reason for that?...as why you want that instead of pointing to the same object?
    – Iron Fist
    Commented Feb 29, 2016 at 5:07
  • Yes, why do you want them distinct and why is copy.copy not satisfactory?
    – Brian Cain
    Commented Feb 29, 2016 at 5:11
  • As defined, both Line and Point could easily be redefined as namedtuples. They'd be immutable, and perhaps would enforce the exclusivity you would prefer. copy.copy would still work, as would creating new instances.
    – Brian Cain
    Commented Feb 29, 2016 at 5:13

1 Answer 1

3

Use the copy module:

import copy

def __init__(self, point0, point1):

        self.point0 = copy.copy(point0)
        self.point1 = copy.copy(point1)

This is required if your point objects are mutable, such as a lists or dictionaries. If you are using immutable types, such as a tuple, then it would not be required to make a copy.

If your points are represented as lists, you can also make a copy of the list using this syntax:

self.point0 = point0[:]
self.point1 = point1[:]

I could advise you with more certainty if you provided the definition of your point class.


Update after OP has posted Point class definition:

If copy.copy() is undesirable (why?) you can manually copy the attributes to the new Point instances:

class Line(object):
    def __init__(self, point0, point1):
        self.point0 = Point(point0.x, point0.y)
        self.point1 = Point(point1.x, point1.y)
3
  • @cleacrij Please post the definition of your Point class in you question.
    – mhawke
    Commented Feb 29, 2016 at 5:09
  • 1
    One way is to use tuples, or even collections.namedtuple for your Points... depends on what else your class is doing..
    – mhawke
    Commented Feb 29, 2016 at 5:11
  • @cleacrij: If you want to continue with your Point class then you need to use copy.copy(), or create Point instances in Line.__init__() as shown in the update to my answer.
    – mhawke
    Commented Feb 29, 2016 at 5:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.