Explain the following with an example

i) isinstance()

Used to check if an object is an instance of a specific class.

Example:

>>> isinstance(p, Point)
True

This returns True if p is an instance of the Point class.


ii) hasattr()

Used to check if an object has a specific attribute.

Example:

>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False

Checks whether the attribute 'x' or 'z' exists in object p.


iii) copy.copy

Performs a shallow copy of an object. Copies the object but not the embedded objects.

Example:

>>> import copy
>>> p2 = copy.copy(p1)
>>> p1 is p2
False

p1 and p2 are different objects, but p2 is a shallow copy of p1.


iv) copy.deepcopy

Performs a deep copy of an object. Copies both the object and all objects it refers to.

Example:

>>> box3 = copy.deepcopy(box)
>>> box3 is box
False
>>> box3.corner is box.corner
False

box3 and box are completely independent after deep copy.

Leave a Reply

Your email address will not be published. Required fields are marked *