Skip to content

Instantly share code, notes, and snippets.

@harunyasar
Created March 20, 2017 11:53
Show Gist options
  • Save harunyasar/c3bacfc65b0b8b6573c3995e21b89f51 to your computer and use it in GitHub Desktop.
Save harunyasar/c3bacfc65b0b8b6573c3995e21b89f51 to your computer and use it in GitHub Desktop.
How to use Python function decorators in a class?
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