6
In some languages, besides being able to instantiate 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 state of the original.
For example, if I wanted to modify a copy of an object DateTime
in PHP, to use the same information as the date of the object of that instance, but having an instance only with the modified time, I could do so:
$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 the date information, but I just cloned and modified it to the time I needed.
Of course, the above was just an example, but there are still other cases where the creation of a new instance of an object could become complicated, due to dependencies of 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, as I noticed) are objects. However, when it comes to class instances, there is some way to clone objects like in PHP?
To stop creating an instance of a Python class we don’t need an operator new
, as in PHP.
So what would be the way to clone an Object in Python? There is a specific operator for this?
Another thing is that in PHP we can use a magic method within the class called __clone
to determine the behaviour of that class when a clone is created.
What about in Python? Is there a special method to modify the behavior of the class in relation to the creation of a clone?
Wallace will be looking for something like https://docs.python.org/3.5/library/copy.html, http://www.python-course.eu/deep_copy.php?
– Miguel
Like this. Interesting to know that Python solved this with a module...
– Wallace Maxters