2

Is it possible in Python to copy an object of a custom class on assignment?

Meaning,

a = b

would effectively do

a = copy.copy(b)

, where a is a new variable, and b an instance of the custom class.

I guess there might be a customization function such as __assign__, but i didn't find anything in the operator-to-function table at the bottom of this page.

Bastian35022
  • 1,092
  • 1
  • 10
  • 18
  • No, you can't customise assignment. What's the problem you're actually trying to solve? Should the instances just be immutable? – jonrsharpe Jul 20 '15 at 11:23
  • I don't want changes on immutable attributes of `b` be reflected in `a`'s attributes, which is why i need to copy the object. The class simply describes the position in a bitstream, so at a first glance it seems to be an integer, making it a popular source for bugs when assigning (and later comparing) instances of the class. Sorry for the duplicate, searched for the wrong keywords apparently. – Bastian35022 Jul 20 '15 at 11:37
  • My point is that you don't *need* to copy the object - if *the instance itself* is immutable, then when you change `a` that won't alter `b` and vice-versa. See e.g. http://stackoverflow.com/q/4828080/3001761 – jonrsharpe Jul 20 '15 at 12:24
  • But if the instance itself is immutable, i won't be able to modify its attributes at all, or did i get something wrong? I definitely need to modify the attributes. – Bastian35022 Jul 20 '15 at 13:00
  • No, you wouldn't, that's the whole point of immutability; instead, any "changes" actually create a new object the new attributes. If you need mutable objects, then you will have to explicitly copy them. – jonrsharpe Jul 20 '15 at 13:01
  • Okay. Thanks a lot for your help. – Bastian35022 Jul 20 '15 at 13:01

0 Answers0