Created
November 20, 2016 00:37
-
-
Save ellieayla/25e4db0edd3534ab732d6ff615ca9fc1 to your computer and use it in GitHub Desktop.
Abstract Base Classes compatible with Python 2 and 3
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
#!/usr/bin/env python | |
# Abstract Base Classes compatible with Python 2 and 3. | |
# https://www.reddit.com/r/learnpython/comments/5duj7z/started_my_first_python_project_ever_need_help/ | |
import abc | |
ABC = abc.ABCMeta('ABC', (object,), {}) | |
class Base(ABC): | |
@abc.abstractmethod | |
def missing(self): | |
pass | |
class MissingImplementations(Base): | |
pass | |
class MyImplementedClass(Base): | |
def missing(self): | |
pass | |
if __name__ == "__main__": | |
for clazz in [MyImplementedClass, MissingImplementations, Base]: | |
print("Attempting to create %s" % clazz) | |
assert issubclass(clazz, Base) | |
try: | |
c = clazz() | |
print("OK: %s" % c) | |
except TypeError as e: | |
print("TypeError: %s" % e) | |
""" | |
$ python3.5 5duj7z.py | |
Attempting to create <class '__main__.MyImplementedClass'> | |
OK: <__main__.MyImplementedClass object at 0x1014172e8> | |
Attempting to create <class '__main__.MissingImplementations'> | |
TypeError: Can't instantiate abstract class MissingImplementations with abstract methods missing | |
Attempting to create <class '__main__.Base'> | |
TypeError: Can't instantiate abstract class Base with abstract methods missing | |
$ python2.7 5duj7z.py | |
Attempting to create <class '__main__.MyImplementedClass'> | |
OK: <__main__.MyImplementedClass object at 0x10ec56210> | |
Attempting to create <class '__main__.MissingImplementations'> | |
TypeError: Can't instantiate abstract class MissingImplementations with abstract methods missing | |
Attempting to create <class '__main__.Base'> | |
TypeError: Can't instantiate abstract class Base with abstract methods missing | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment