In some languages, in addition to instantiating a class to construct a given object, we can also clone an existing instance, if we want an object with the same characteristics of the current instance, but without changing the original state. p>
For example, if I wanted to modify a copy of a DateTime
object in PHP, to use the same date information as the object of that instance, but having an instance with only the modified time, I could do this: p>
$date = new Date('2015-01-01 00:00:00');
$date2 = clone $date;
// não precisei redefinir a data, mas só a hora
$date2->setTime(23, 59, 59);
Above, it was not necessary to create a new instance with date information, but I just cloned and modified it for the time I needed.
Of course, above was just an example, but there are still other cases where creating a new instance of an object could become complicated due to dependencies on an object. Then we can clone to have the same information in a new object, but without modifying the original.
In Python I also realize that everything (or almost everything up, where I realized it) are objects. But when it comes to class instances, is there any way to clone objects like they do in PHP?
To stop creating an instance of a class in Python we do not need a new
operator, as in PHP.
So how would you clone an Object in Python? Is there a specific operator for this?
Another thing is that in PHP we can use a magic method inside the class called __clone
to determine the behavior of that class when a clone is created.
What about Python? Is there a special method for modifying the behavior of the class in relation to creating a clone?