Copy constructors in python.

In Python, while there isn’t a traditional copy constructor like in languages such as C++, you can achieve the same functionality by overriding the __init__ method or using a class method to create a new instance that copies the attributes of another instance. Here’s how you can implement a copy constructor-like functionality in Python

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Point(x={self.x}, y={self.y})"
    
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
    
    @classmethod
    def from_point(cls, point):
        return cls(point.x, point.y)

# Example usage:
point1 = Point(3, 4)
point2 = Point.from_point(point1)

print("Original Point:", point1)
print("Copied Point:", point2)

OUTPUT:

Original Point: Point(x=3, y=4)
Copied Point: Point(x=3, y=4)

POINTS:

Class Definition (Point):

__init__(self, x, y): Initializes a Point object with coordinates x and y.
__str__(self) and __repr__(self): Provide string representations of the Point object for printing and debugging.
Class Method (from_point):

@classmethod: Decorator that defines a method that operates on the class itself rather than on instances.
from_point(cls, point): Class method that creates a new instance of Point (cls) using coordinates from another Point object (point).
Example Usage:

Create an instance point1 of Point with coordinates (3, 4).
Use Point.from_point(point1) to create point2, which is a copy of point1.
Print both point1 and point2 to demonstrate that point2 is a copy of point1.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top