0 votes
in Python by
Explain delegation in Python

1 Answer

0 votes
by

Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x. The example shows a class that captures the behavior of the file and converts data from lower to uppercase.

class upcase:

def __init__(self, out):

self._out = out

def write(self, s):

self._outfile.write(s.upper())

def __getattr__(self, name):

return getattr(self._out, name)

The write() method is used in the upcase class converts the string to the uppercase before calling another method. The delegation is being given using the self.__outfile object.

Related questions

+1 vote
asked Feb 13, 2023 in Python by rajeshsharma
0 votes
asked Oct 27, 2022 in Python by SakshiSharma
...