osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Copy constructor and assignment operator


On 2018-09-15 19:47, Ajay Patel wrote:
> 
> I have created below code and i want to restrict an object copy.
> What are the methods called for copy constructor and assignment operator? Basically i don't want to allow below operation.
> 
> p = Point(1,3)
> p2 = Point(6,7)
> 
> => How to disallow below operations?
> p(p2)
> p = p2
> 
> Please point out a documentation for the same if available.
> 
> 
> class Point:
> 
>          def _init_(self, x = 0, y = 0):
>                  self.x = x
>                  self.y = y
> 
>          def _str_(self):
>                  return "({0},{1})".format(self.x,self.y)
> 
>          def _repr_(self):
>                  return "({0},{1})".format(self.x,self.y)
> 
>          def _call_(self,other):
>                  print("_call_")
>                  self.x = other.x
>                  self.y = other.y
> 
>          def _setattr_(self, name, value):
>                  print("_setattr_",name,value)
> 

"__init__", etc, are referred to as "dunder" methods because they have 
double leading and trailing underscores. Those that you wrote have only 
single leading and trailing underscores.

The term "copy constructor" is something from C++. It doesn't exist in 
Python.

Assignment statements _never_ copy an object. If you want a copy of an 
object, you have to be explicit.

Writing:

p = p2

will merely make 'p' refer to the same object that 'p2' currently refers to.

For making a copy of an object, have a look at the "copy" module.