python$ python method_not_imlemented_mixin.py
Foo.foo()
Bar.bar()
42
Traceback (most recent call last):
File "method_not_imlemented_mixin.py", line 33, in <module>
Foo().bar() # Error
File "method_not_imlemented_mixin.py", line 6, in _method_not_implemented
raise NotImplementedError("Method %s is not implemented in class %s" % (name, self.__class__.__name__))
NotImplementedError: Method bar is not implemented in class Foo
Last active
September 20, 2018 13:27
-
-
Save eagafonov/c3ad34619ed2fe8f81b803d0691ba3b8 to your computer and use it in GitHub Desktop.
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 GetAttrNotImplementedMixin: | |
methods_to_be_implemented = {'foo', 'bar'} # add more method names | |
def __getattr__(self, name): | |
def _method_not_implemented(*args, **kwargs): | |
raise NotImplementedError("Method %s is not implemented in class %s" % (name, self.__class__.__name__)) | |
if name in self.methods_to_be_implemented: | |
return _method_not_implemented | |
raise AttributeError(self.__class__, name) | |
class Foo(GetAttrNotImplementedMixin): | |
def __init__(self): | |
self.the_answer = 42 | |
# Foo.bar is not implemented | |
def foo(a): | |
print('Foo.foo()') | |
class Bar(GetAttrNotImplementedMixin): | |
# Bar.foo is not implemented | |
def bar(a): | |
print('Bar.bar()') | |
Foo().foo() # OK | |
Bar().bar() # OK | |
print(Foo().the_answer) | |
Foo().bar() # Error | |
# print(Bar().the_answer) # Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment