Created
June 3, 2019 21:21
-
-
Save lmazuel/1840fdf15099c757c6a863fe9b60a76e to your computer and use it in GitHub Desktop.
Metaclass
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 functools import wraps | |
from six import add_metaclass | |
class MetaCount(type): | |
def __new__(cls, *args, **kwargs): | |
obj = super(MetaCount, cls).__new__(cls, *args, **kwargs) | |
obj.read_count = 0 | |
if hasattr(obj, 'read'): | |
original_read = obj.read | |
@wraps(original_read) | |
def read_count(*args, **kwargs): | |
obj.read_count += 1 | |
return original_read(*args, **kwargs) | |
obj.read = read_count | |
return obj | |
@add_metaclass(MetaCount) | |
class Toto(object): | |
def read(self): | |
"""MyDoc.""" | |
return "Foo" | |
t = Toto() | |
t.read() | |
t.read() | |
assert "MyDoc" in t.read.__doc__ | |
assert t.read_count == 2 | |
assert t.read() == "Foo" | |
assert t.read_count == 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment