Demo entry 6776226

AAdapter abstract

   

Submitted by anonymous on Nov 30, 2018 at 12:41
Language: Python. Code size: 1.7 kB.

class Elf:
    name = 'Rosalor'

    def le_suilon(self):
        print('Elf {name} says: Greeting'.format(name=self.name))


class Orc:
    name = 'Khadgar'

    def mok_rah(self):
        print('Orc {name} says: Greeting'.format(name=self.name))


class Human:
    name = 'Severus Smithy'

    def say_hello(self):
        print('Human {name} says: Greeting'.format(name=self.name))


class HeroAdapter:
    _initialised = False

    def __init__(self, hero, **adapted_methods):
        super().__init__()

        self.hero = hero

        for key, value in adapted_methods.items():
            func = getattr(self.hero, value)
            self.__setattr__(key, func)

        self._initialised = True

    def __getattr__(self, attr):
        return getattr(self.hero, attr)

    def __setattr__(self, key, value):
        if not self._initialised:
            super().__setattr__(key, value)
        else:
            setattr(self.hero, key, value)


if __name__ == '__main__':
    hero_adapters = [
        HeroAdapter(Human(), call_me='say_hello'),
        HeroAdapter(Elf(), call_me='le_suilon'),
        HeroAdapter(Orc(), call_me='mok_rah')
    ]

    for hero in hero_adapters:
        hero.call_me()

    human_adapter = hero_adapters[0]

    print('\n')
    print('Name from HumanAdapter: {}'.format(human_adapter.name))
    print('Name from HumanAdapter: {}'.format(human_adapter.hero.name))

    hero_adapters[0].name = 'Arne Allerton'

    print('\n')
    print('Name from HumanAdapter: {}'.format(human_adapter.name)
    print('Name from HumanAdapter: {}'.format(human_adapter.hero.name)

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).