Created
March 20, 2017 11:53
-
-
Save harunyasar/c3bacfc65b0b8b6573c3995e21b89f51 to your computer and use it in GitHub Desktop.
How to use Python function decorators in a class?
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
class Lightning: | |
lights_on = 'ON' | |
lights_off = 'OFF' | |
def button_action(action_type): | |
def action_decorator(func): | |
def action_wrapper(self): | |
if action_type == 'on': | |
print(self.lights_on) | |
func(self) | |
if action_type == 'off': | |
print(self.lights_off) | |
return action_wrapper | |
return action_decorator | |
@button_action('off') | |
def enlight_off(self): | |
print('Enlight me!') | |
@button_action('off') | |
def enlight_on(self): | |
print('Enlight me!') | |
if __name__ == '__main__': | |
test = Lightning() | |
test.enlight_on() | |
print('-----') | |
test.enlight_off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment