-
-
Save rokcarl/771ccef703b287705a5a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 __future__ import print_function | |
from functools import wraps | |
class Fish(object): | |
def __new__(cls, *args, **kwargs): | |
o = super(Fish, cls).__new__(cls, *args, **kwargs) | |
o.type = 'goldfish' | |
for name, val in vars(cls).items(): | |
if name.startswith('foo_') and callable(val): | |
setattr(o, name, Fish.deco(val, o)) | |
return o | |
def extra(self): | |
print("*" * 15) | |
@staticmethod | |
def deco(func, o): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
return "bar :: " + func(o, *args, **kwargs) | |
return wrapper | |
class Cat(Fish): | |
def __init__(self): | |
if not hasattr(self, 'type'): | |
self.type = 'pussycat' | |
def iam(self): | |
print('I am a', self.type) | |
def foo_name(self): | |
print('this should be shown only once') | |
return "lola" | |
def foo_type(self): | |
return "ani" | |
def main(): | |
""" | |
>> main() | |
*************** | |
I am a goldfish | |
*************** | |
bar :: lola | |
bar :: ani | |
""" | |
cat = Cat() | |
cat.extra() | |
Cat().iam() | |
cat.extra() | |
print(cat.foo_name()) | |
print(cat.foo_name()) | |
print(cat.foo_type()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment