Created
August 18, 2022 12:42
-
-
Save marekyggdrasil/2e921185cad16cde3720b256b1325efe to your computer and use it in GitHub Desktop.
how to use class decorators with arguments in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
class ForbiddenDrink: | |
def __init__(self, drinks): | |
self.do_not_drink_that = drinks | |
def __call__(self, func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
innerself = args[0] | |
drink = args[1] | |
if drink in self.do_not_drink_that: | |
raise Exception('DO NOT DRINK!') | |
return func(*args, **kwargs) | |
return wrapper | |
class Driver: | |
@ForbiddenDrink(['alcohol', 'beer', 'wine']) | |
def drink(self, beverage): | |
print('I drink ' + beverage + ' and drive') | |
class DietPerson: | |
@ForbiddenDrink(['soda', 'milktea']) | |
def drink(self, beverage): | |
print('I drink ' + beverage + ' and keep my diet') | |
johnny = Driver() | |
johnny.drink('tea') | |
johnny.drink('soda') | |
johnny.drink('alcohol') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment