# Input 2: Having incompatible (non-USB type C) devices:classPrinter:name="Printer"defconnect_usb_b(self):returnf"{self.name} is connected: Printing..."# Input 2: Having incompatible (non-USB type C) devices:classFlash:name="Flash"defconnect_usb_a(self):returnf"{self.name} is connected: Copying..."# Input 2: Having incompatible (non-USB type C) devices:classMonitor:name="Monitor"defconnect_hdmi(self):returnf"{self.name} is connected: Displaying..."
Expected Output:
Making that non-USB type C devices have USB type C port
Printer (USB type C)
Flash (USB type C)
Monitor (USB type C)
MacBook is able to connect to those incompatible devices
1
2
3
Printer is connected: Printing...
Flash is connected: Copying...
Monitor is connected: Displaying...
How to implement Adapter?
Non-Adapter implementation:
1
2
3
4
5
6
7
8
9
10
11
12
if__name__=="__main__":devices=[Printer(),Flash(),Monitor()]fordeviceindevices:ifisinstance(device,Printer):# Expected Output 2: MacBook is able to connect to those incompatible devicesprint(device.connect_usb_b())elifisinstance(device,Flash):# Expected Output 2: MacBook is able to connect to those incompatible devicesprint(device.connect_usb_a())elifisinstance(device,Monitor):# Expected Output 2: MacBook is able to connect to those incompatible devicesprint(device.connect_hdmi())
classAdapter:def__init__(self,obj,**adapted_methods):self.obj=objself.__dict__.update(adapted_methods)def__getattr__(self,attr):returngetattr(self.obj,attr)if__name__=="__main__":devices=[]printer=Printer()# Expected Output 1: Making that non-USB type C devices have USB type C portdevices.append(Adapter(printer,connect=printer.connect_usb_b))flash=Flash()# Expected Output 1: Making that non-USB type C devices have USB type C portdevices.append(Adapter(flash,connect=flash.connect_usb_a))monitor=Monitor()# Expected Output 1: Making that non-USB type C devices have USB type C portdevices.append(Adapter(monitor,connect=monitor.connect_hdmi))fordeviceindevices:# Expected Output 2: MacBook is able to connect to those incompatible devicesprint(device.connect())