Copy constructor in python?

后端 未结 7 926
逝去的感伤
逝去的感伤 2020-11-29 02:29

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 t

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:44

    In python the copy constructor can be defined using default arguments. Lets say you want the normal constructor to run the function non_copy_constructor(self) and the copy constructor should run copy_constructor(self, orig). Then you can do the following:

    class Foo:
        def __init__(self, orig=None):
            if orig is None:
                self.non_copy_constructor()
            else:
                self.copy_constructor(orig)
        def non_copy_constructor(self):
            # do the non-copy constructor stuff
        def copy_constructor(self, orig):
            # do the copy constructor
    
    a=Foo()  # this will call the non-copy constructor
    b=Foo(a) # this will call the copy constructor
    

提交回复
热议问题