Special Method Protocols

__copy__() — copy protocol

Customize copy.copy() for a class. A shallow copy typically creates an outer object while retaining references to nested values. Immutable objects may legitimately return themselves.

Formal Syntax & Structure

python syntaxpython
def __copy__(self):

Return Value

object

Shallow copy.

Working Example

Example Snippetpython
import copyclass Bag:    def __init__(self,items): self.items=items    def __copy__(self): return Bag(self.items)def demo():    original=Bag([1]); clone=copy.copy(original)    return clone is not original, clone.items is original.itemsprint(demo())
Python Reference