Python prototype mode

Python prototype mode

Prototype design pattern helps us create clones of objects. Its simplest form is a
clone() function, which accepts an object as an input parameter and returns a copy of the input object. In Python, this can be
done using the copy.deepcopy() function. Let's look at an example. The following code (file clone.py) has two classes,
A and B. A is the parent class and B is the derived class/child class. In the main program part, we create an instance b of class B, and use deepcopy() to
create a clone c of b. The result is that all members have been copied to clone c. The following is a code demonstration. As an interesting
exercise, you can also try to use deepcopy() on the combination of objects.

import copy


class A:
    def __init__(self):

        self.x = 18
        self.msg = 'Hello'


class B(A):
    def __init__(self):

        A.__init__(self)
        self.y = 34

    def __str__(self):

        return '{}, {}, {}'.format(self.x, self.msg, self.y)


if __name__ == '__main__':
    b = B()
    c = copy.deepcopy(b)
    print([str(i) for i in (b, c)])
    print([i for i in (b, c)])

Insert picture description here

Guess you like

Origin blog.csdn.net/qestion_yz_10086/article/details/108258696