0

To keep it simple, I wanna do a new type that emulate a coordinate in 2D space.

class Vector2:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)
    def __str__(self):                 # for print()
        return f"({self.x}, {sefl.y})"

But I went into a problem, when I assign a vector to another variable, any change to one of them will affect both.

>>> A = Vector2(1.0, 2.0)
>>> B = A                 # my problem is that
>>> A.x = 2.0             # changing the x attribute of A
>>> print(B)              # affect B and I don't want that
(2.0, 2.0)

I know some special methods (__set__ or __get__) exist which can make that when writing this B = A, B will be a copy of A instead of A himself.

Now, what special method should I use and how should I use it?

I tried to find an anwser there but I didn't found.

specification: I'm using python3.9.5 on linux

superfred
  • 3
  • 4
  • [how-to-copy-a-python-class](https://stackoverflow.com/questions/9541025/how-to-copy-a-python-class) ? – Patrick Artner Feb 18 '22 at 23:27
  • I think you didn't understand my question @PatrickArtner , I don't want to manually make a copy, I want the process to be automatically called when I type `A = B`. Does it's possible? – superfred Feb 21 '22 at 23:57
  • That is not how python works. Create a function accepts "a thing" and returns "a copied thing" - you would need to use `B = give_me_a_copy_of(A)` instead of `B = A` then. – Patrick Artner Feb 22 '22 at 07:22

0 Answers0