flamenco
flamenco

Reputation: 2840

Create an object that has methods deferred to a different object for execution [Python]

To explain it and for simplicity, I will use the power domain example.
Imagine that you have more than one equipment. All plugged in one power strip with multiple plugs. The power strip can be controlled via an Ethernet or some other means. Out of all these, there is one and only one which can actually turn power on and off. Nevertheless, I would like the rest of equipment pieces to "appear" as being capable to control the power switch, as well. Programmatically, such functions can look something like:

pwr.poweron()  # this instance can do the actual poweron/poweroff via remote control
eq1.poweron()
eq2.poweron()

where eq1, eq2 are instances of some class. eq1 and eq2 just appear as being able to control the power. In reality, they defer poweron/poweroff for execution to instance pwr. How would you design such class in Python?

Upvotes: 1

Views: 82

Answers (1)

dlask
dlask

Reputation: 9002

For example:

class Pwr(object):

    def __init__(self):
        pass

    def poweron(self):
        pass

class Eqp(object):

    def __init__(self, pwr):
        self.pwr = pwr

    def poweron(self):
        self.pwr.poweron()

pwr = Pwr()
eq1 = Eqp(pwr)
eq2 = Eqp(pwr)

Upvotes: 3

Related Questions