Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

In python, how can/should decorators be used to implement function polymorphism?

$
0
0

Supposing we have a class as follows:

class PersonalChef():    def cook():        print("cooking something...")

And we want what it cooks to be a function of the time of day, we could do something like this:

class PersonalChef():    def cook(time_of_day):        ## a few ways to do this, but this is quite concise:        meal = {'morning':'breakfast', 'midday':'lunch', 'evening':'dinner'}[time_of_day]        print("Cooking", meal)PersonalChef().cook('morning')>>> Cooking breakfast

A potentially nice syntax form for this would be using decorators. With some under-the-hood machinery buried inside at_time, it ought to be possible to get it to work like this:

class PersonalChef():    @at_time('morning')    def cook():        print("Cooking breakfast")    @at_time('midday')    def cook():        print("Cooking lunch")    @at_time('evening')    def cook():        print("Cooking dinner")PersonalChef().cook('morning')>>> Cooking breakfast

The reason this could be a nice syntax form is shown by how it then shows up in subclasses:

class PersonalChefUK(Personal_Chef):    @at_time('evening')    def cook():        print("Cooking supper")

The code written at the sub-class level is extremely minimal and doesn't require any awareness of the base-class implementation/data structures and doesn't require any calls to super() to pass-through the other scenarios. So it could be nice in a situation where there are a large number of people writing derived-classes for whom we want to pack and hide complexity away in the base class and make it hard for them to break the functionality.

However, I've tried a few different ways of implementing this and gotten stuck. I'm quite new to decorators, though, so probably missing something important. Any suggestions/comments?


Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>