Copy constructor in python?

Viewed 84928

Is there a copy constructor in python ? If not what would I do to achieve something similar ?

The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.

8 Answers

I think you want the copy module

import copy

x = copy.copy(y)        # make a shallow copy of y
x = copy.deepcopy(y)    # make a deep copy of y

you can control copying in much the same way as you control pickle.

For your situation, I would suggest writing a class method (or it could be a static method or a separate function) that takes as an argument an instance of the library's class and returns an instance of your class with all applicable attributes copied over.

The following solution probably repeats some of the previous ones in a simple form. I don't know how it is "pythocally" right, but it works and was quite convenient in the certain case I used it.

class Entity:
    def __init__(self, code=None, name=None, attrs=None):
        self.code = code
        self.name = name
        self.attrs = {} if attrs is None else attrs


    def copy(self, attrs=None):
        new_attrs = {k: v.copy() for k, v in self.attrs.items()} if attrs is None else attrs
        return Entity(code=self.code, name=self.name, attrs=new_attrs)

Usage:

new_entity = entity.copy()

This is a more complicated version that allows to interfere in the copying process. I used it in only one place. Also note that objects contained in self.attrs also have such kind of "copying constructor".

This solution is not generic but is very simple and provides quite much control.

you can achieve like this code without using any copy module Python dosen't support method overloding so we can not make copy constructor ##

class student():
    name: str
    age: int

    def __init__(self, other=None):
        if other != None and isinstance(other, student):
            self.name = other.name
            self.age = other.age
        elif not(isinstance(other,student)) and other!=None:
            raise TypeError
    def printInfo(s):
        print(s.name, s.age)
Related