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
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)