Created
September 28, 2021 05:39
-
-
Save laalaguer/2c4b3039a86326939772b0e8658c6c32 to your computer and use it in GitHub Desktop.
Python3 Interface and Abstract class
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
import abc | |
class MyInterface(abc.ABC): # Same as class MyInterface(metaclass=abc.ABCMeta) | |
def __init__(self, age: int): | |
print('MyInterface: init') | |
self.age = age | |
@abc.abstractmethod | |
def load_data(self, name: str): | |
# Notice abstract method can contain actual code | |
print('MyInterface: load_data') | |
print(f'MyInterface: age={self.age}') | |
class B (MyInterface): | |
def __init__(self, age: int): | |
super().__init__(age) | |
print('B: init') | |
def load_data(self, name: str): | |
super().load_data(name) # Notice there is no param in super() | |
print('B: load_data') | |
print(f'is subclass: B => MyInterface, {issubclass(B, MyInterface)}') | |
print(f'Method Resolution Order (MRO): {B.__mro__}') | |
b = B(13) | |
b.load_data('hahaha') | |
print(f'is instance: b => MyInterface, {isinstance(b, MyInterface)}') | |
# is subclass: B => MyInterface True | |
# Method Resolution Order (MRO): (<class '__main__.B'>, <class '__main__.MyInterface'>, <class 'abc.ABC'>, <class 'object'>) | |
# MyInterface: init | |
# B: init | |
# MyInterface: load_data | |
# MyInterface: age=13 | |
# B: load_data | |
# is instance: b => MyInterface True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment