Copy constructor in python?

后端 未结 7 923
逝去的感伤
逝去的感伤 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:40

    I have a similar situation differing in that the new class only needs to copy attributes. Thus using @Dunham's idea and adding some specificity to @meisterluk's suggestion, @meisterluk's "copy_constructor" method could be:

    from copy import deepcopy
    class Foo(object):
        def __init__(self, myOne=1, other=None):
        self.two = 2
        if other <> None:
            assert isinstance(other, Foo), "can only copy instances of Foo"
            self.__dict__ = deepcopy(other.__dict__)
        self.one = myOne
    
    def __repr__(self):
        out = ''
        for k,v in self.__dict__.items():
            out += '{:>4s}: {}, {}\n'.format(k,v.__class__,v)
        return out
    
    def bar(self):
        pass
    
    foo1 = Foo()
    foo2 = Foo('one', foo1)
    
    print '\nfoo1\n',foo1
    print '\nfoo2\n',foo2
    

    The output:

    foo1
     two: , 2
     one: , 1
    
    
    foo2
     two: , 2
     one: , one
    

提交回复
热议问题